Blog

A catalogue of my discoveries in software development and related subjects, that I think might be of use or interest to everyone else, or to me when I forget what I did!

C# HttpClient for Calling Azure based WebAPI with OAuth Client Credentials

January 06, 2017

The below C# code creates a sub-class of the System.Net.Http.HttpClient that deals with adding the "Authorization" header to subsequent calls, using OAuth client credentials grant.
using System;
using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json.Linq;

namespace SomeProject.WebAPI.Client
{
    internal sealed class SomeWebApiHttpClient : HttpClient
    {
        private static string authToken;
        private static DateTime authTokenTime;

        private SomeWebApiHttpClient(ISomeWebApiClientConfig config)
        {
            this.BaseAddress = new Uri(config.SomeWebApiBaseAddress);
        }
        
        public static async Task<SomeWebApiHttpClient> CreateInstanceAsync(ISomeWebApiClientConfig config)
        {
            var instance = new SomeWebApiHttpClient(config);
            instance.DefaultRequestHeaders.Add("Authorization", await GetAuthAsync(config.SomeWebApiTenantId, config.CallingClientId, config.CallingClientKey));

            return instance;
        }

        private static async Task<string> GetAuthAsync(string tenantId, string callingClientId, string callingClientKey)
        {
            if (string.IsNullOrEmpty(authToken) || DateTime.Now.Subtract(authTokenTime).TotalMinutes > 45)
            {
                using (var authClient = new HttpClient())
                {
                    authClient.BaseAddress = new Uri("https://login.microsoftonline.com/");

                    Dictionary<string, string> bodyContent = new Dictionary<string, string>();
                    bodyContent.Add("grant_type", "client_credentials");
                    bodyContent.Add("client_id", callingClientId);
                    bodyContent.Add("client_secret", callingClientKey);
                    bodyContent.Add("resource", "https://somedomain.onmicrosoft.com/APP-URI-ID");

                    var result = await authClient.PostAsync(
                        $"{tenantId}/oauth2/token",
                        new FormUrlEncodedContent(bodyContent)).ConfigureAwait(false);

                    if (result.IsSuccessStatusCode)
                    {
                        dynamic tokenResult = (dynamic)JValue.Parse(await result.Content.ReadAsStringAsync().ConfigureAwait(false));

                        authToken = $"{tokenResult.token_type} {tokenResult.access_token}";
                        authTokenTime = DateTime.Now;
                    }
                    else
                    {
                        Trace.WriteLine($"Failed to login to API - {await result.Content.ReadAsStringAsync().ConfigureAwait(false)}");
                        
                        return string.Empty;
                    }
                }
            }

            return authToken;
        }
    }
}
In the above code you must correctly set the domain and APP-URI-ID for the WebAPI this client is supposed to be using (or pass them in the config if they are variable). The configuration is passed in via an interface so that the calling code can inject whatever implementation they have for storing the configuration. E.g. In the web project composition root, a class that reads from the web.config using ConfigurationManager. The interface is defined as below:
public interface ISomeWebApiClientConfig
    {
        string SomeWebApiBaseAddress { get; }
        string SomeWebApiTenantId { get; }
        string CallingClientId { get; }
        string CallingClientKey { get; }
    }
These settings can be found in the Azure portal within the active directory that defines the client/server applications. Now the rest of the code base can use this client to call the API's endpoints, without worrying about injecting the auth header. Example usage of the HttpClient to call an example API endpoint:
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json.Linq;

namespace SomeProject.WebAPI.Client
{
    public class ExampleDataClient
    {
        private readonly ISomeWebApiClientConfig config;

        public ExampleDataClient(ISomeWebApiClientConfig config)
        {
            this.config = config;
        }

        public async Task<IEnumerable<SomeExampleData>> GetSomeExampleData(string someParam)
        {
            using (var client = await SomeWebApiHttpClient.CreateInstanceAsync(this.config).ConfigureAwait(false))
            {
                var result = await client.GetAsync($"api/SomeExampleData").ConfigureAwait(false);

                if (result.IsSuccessStatusCode)
                {
                    var returnValue = JValue.Parse(await result.Content.ReadAsStringAsync().ConfigureAwait(false));

                    if (returnValue.HasValues)
                    {
			List<SomeExampleData> outputList = new List<SomeExampleData>();
                       foreach (var item in returnValue)
                       {
                           outputList.Add(SomeExampleData.FromJObject(item));
                       }
                       
                       return outputList.AsEnumerable();
                    }
                    else
                    {
                        return Task.FromResult<IEnumerable<SomeExampleData>>(null);
                    }
                }
                else
                {
                    Trace.WriteLine($"HTTP error: {result.RequestMessage.RequestUri} ({result.StatusCode}) - {await result.Content.ReadAsStringAsync().ConfigureAwait(false)}");
                    return Task.FromResult<IEnumerable<SomeExampleData>>(null);
                }
            }
        }
    }
}
Permalink: C# HttpClient for Calling Azure based WebAPI with OAuth Client Credentials

Exception Handling in ASP.NET MVC and WebAPI

January 04, 2017

This is an amalgmation of techniques taken from various sources on how best to handle exceptions/errors in ASP.NET MVC. There are many ways to approach this, but this is one that I'm happy with at the moment, it is based on the premise that the application doesn't swallow up exceptions in try catch blocks and silently fail, instead the error is logged and then reported to the user so they can make a decision as to whether they can fix the issue/try again to resolve (e.g. for validation exceptions). Firstly, override the "Application_Error" in the global.asax so that any unhandled exceptions are caught and handled in a nicer way than the "yellow screen of death" provided by ASP.NET.
/// <summary>
/// http://www.codeproject.com/Articles/422572/Exception-Handling-in-ASP-NET-MVC#handleerror
/// http://prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc#elmah
/// http://stackoverflow.com/questions/5226791/custom-error-pages-on-asp-net-mvc3
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">Args</param>
protected void Application_Error(object sender, EventArgs e)
{
    var httpContext = ((MvcApplication)sender).Context;

    var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
    var currentController = " ";
    var currentAction = " ";

    if (currentRouteData != null)
    {
        if (currentRouteData.Values["controller"] != null && !string.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
        {
            currentController = currentRouteData.Values["controller"].ToString();
        }

        if (currentRouteData.Values["action"] != null && !string.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
        {
            currentAction = currentRouteData.Values["action"].ToString();
        }
    }

    var ex = this.Server.GetLastError();
    Trace.TraceError(ex.MessageEx());

    var routeData = new RouteData();
    var controller = new ErrorController();
    var action = "Index";
    int httpStatusCode = (int)HttpStatusCode.InternalServerError;

    if (ex is HttpException)
    {
        var httpEx = ex as HttpException;

        switch (httpEx.GetHttpCode())
        {
            case 404:
                action = "Http404";
                break;

            // define additional http code error pages here
            default:
                action = "Index";
                break;
        }
    }

    httpContext.ClearError();
    httpContext.Response.Clear();
    httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : httpStatusCode;
    httpContext.Response.TrySkipIisCustomErrors = true;
    httpContext.Response.Headers.Add("Content-Type", "text/html");
    routeData.Values["controller"] = "Error";
    routeData.Values["action"] = action;

    controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
    ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
This works by interpreting the exception, logging the error to the trace listeners and then redirecting the users to an "/Error/Index" action (or 404). The content of the error page can be something like this:
@model HandleErrorInfo

@{
    ViewBag.Title = "Error";
}

<h1>Error</h1>

<div class="alert alert-danger" role="alert">
    <p><i class="fa fa-warning"></i> Sorry, an error occurred whilst processing your request.</p>
    <p>@Model.Exception.Message</p>
</div>
That will take care of problems in "normal" page loads and postbacks, i.e. non-async calls. For async calls this is handled slightly differently. Create an action filter that will check for exceptions and wrap the message inside a JsonResponse object (see http://www.dotnetcurry.com/ShowArticle.aspx?ID=496 ):
public class HandleJsonExceptionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
            filterContext.Result = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    Message = filterContext.Exception.MessageEx()
                }
            };

            Trace.TraceError(filterContext.Exception.MessageEx());
            filterContext.ExceptionHandled = true;
        }
    }
}
Now decorate the actions you will be calling asynchronously with this attribute, usually these are the actions that return a JsonResult or a Partial View. For a consistent theme, you can return the same response "Message" for your WebAPI calls by applying the following exception filter:
public class HandleExceptionAttribute : ExceptionFilterAttribute, IFilter
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        actionExecutedContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);

        actionExecutedContext.Response.Content = new StringContent(
            JObject.Parse(
                    $"{{'Message': '{actionExecutedContext.Exception.MessageEx().Replace("'", "\"")}'}}"
        ).ToString(), Encoding.UTF8, "application/json");

        Trace.TraceError(actionExecutedContext.Exception.MessageEx() + "Stack:" + actionExecutedContext.Exception.StackTrace);
    }
}


// --- Register this in the WebApiConfig "Register" section..

config.Filters.Add(new HandleExceptionAttribute());
Noting that WebAPI doesn't use the global.asax error handler (since there are no views). Now if you are calling the MVC action or webAPI endpoint from a jQuery style $.Ajax request, then this response object can be read in the fail block of that code structure:
$.ajax({
    url: '/Controller/Action',
    method: "POST",
    data: {
        'example': data
    }
}).done(function (result) {            
        // process a good result
}).fail(function (errorResult) {
    alert("Could not perform the operation\n" + errorResult.responseJSON.Message);
});
If you are using the Ajax.BeginForm approach, you can handle the failure condition by referencing your handler function in the "OnFailure" attribute of "AjaxOptions", (see http://johnculviner.com/ajax-beginform-ajaxoptions-custom-arguments-for-oncomplete-onsuccess-onfailure-and-onbegin/)
Ajax.BeginForm(
        "Controller",
        "Action",
        FormMethod.Post,
        new AjaxOptions()
        {
            HttpMethod = "POST",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "",
            OnSuccess = "HandleGoodResult();",
            OnFailure = "HandleFailure(xhr);"
        }, 
        new { id = "myForm" }))
Finally, you may be calling the API from some c# web client code, so you can parse the error as follows:
public string ParseErrorResponse(string responseText)
{
       string errorText = responseText;

       try
       {
           dynamic errorJson = (dynamic)JToken.Parse(errorText);
           errorText = errorJson.Message;
       }
       catch (Exception)
       {
       }

       return errorText;
}
Note: Remember that the exceptions you allow to arrive to user's browser should be legible and meaningul. Also, some exceptions can be "survived" so no need to bubble them, and finally exceptions in general are costly and so should be avoided in the first place (e.g. add clientside validation, add checks before calling dependencies that throw exceptions). For information on the "MessageEx()" extension, see my other post. NOTE: If you are deploying this website to Azure you will need to add the following tag to your system.webServer node of your web.config
<httpErrors existingResponse="PassThrough"/>
Permalink: Exception Handling in ASP.NET MVC and WebAPI

Exception Extension for Simple Logging

January 03, 2017

There is nothing more annoying than tracing an exception that only says "see inner exception for details". For this reason, I have started to use this simple extension method which traverses the entire exception structure, concatenating the messages together:
internal static class ExceptionExtensions
    {
        public static string MessageEx(this Exception ex)
        {
            StringBuilder errorMessageBuilder = new StringBuilder();

            Exception exception = ex;
            while (exception != null)
            {
                errorMessageBuilder.AppendLine(exception.Message);
                exception = exception.InnerException;
            }

            return errorMessageBuilder.ToString();
        }
    }
Permalink: Exception Extension for Simple Logging

Partially re-hydrating a class instance

August 22, 2016

I was working with some legacy Silverlight code, to add the functionality of saving the current state to a file and re-opening it later. The way that I chose to implement this was simply using the DataContractSerializer to turn the viewmodel state into a string and write it to a file. I marked the viewmodels with the DataContract attribute and marked any user related properties as DataMember. This worked great for saving the state to a file, and to some extent it worked when re-hyrating the state back to a viewmodel instance. However the problem I had, is that the viewmodel instances that are created when the application is initialised are part of a web of events registrations and dependancies between other viewmodels in the app. It was going to be a pain to re-wire the newly hydrated instances into all the places where the "initialised" viewmodels already were. So my solution was to simply "partially re-hydrate" the already existing viewmodel instances. To acheive this with minimal on-going maintenance, I wrote a simple generic class that uses reflection to identify all the DataMember properties of a class and copies the values from one instance to another. I could then re-hydrate an instance from the file and from that partially rehydrate the plumbed in existing instance. Class below:
using System.Runtime.Serialization;

namespace Project.Silverlight.Helpers
{
    public class PartialRehydrator<T>
    {
        public void Rehydrate(T source, T target)
        {
            // loop through each property of the given type
            foreach (var prop in typeof(T).GetProperties())
            {
                // look for the DataMemberAttribute on this property
                var dma = prop.GetCustomAttributes(typeof(DataMemberAttribute), true);

                // if it has a "DMA" then it's in scope for hydration
                if (dma != null && dma.Length > 0)
                {
                    // get the value from the source
                    var sourceValue = prop.GetGetMethod().Invoke(source, null);

                    // copy the value to the target
                    prop.GetSetMethod().Invoke(target, new object[] { sourceValue });
                }
            }
        }
    }
}
Permalink: Partially re-hydrating a class instance

Simple Responsive IFrame using JavaScript

June 23, 2016

I had a requirement to host the content of one responsive web application inside a view of another responsive web application. Since both applications were responsive in design there was no definitive height, width or aspect ratio. I found a tutorial here: https://benmarshall.me/responsive-iframes/ which talks about a library called Pym.js and also has some css/js examples of a simpler approach. I decided that using Pym.js was overkill for my needs, mostly because I didn't want to make any code changes to the target site. The code I found on the above link also didn't quite work for my needs, since I didn't have a particular aspect ratio (it will depend on the viewing device) and also couldn't give a hard-coded initial width/height to the iframe. In my case, the aspect ratio is actually dependant on the viewing devices screen, therefore I changed the script slightly as below:
$(document).ready(function () {
            var $responsive_iframes = $(".responsive_iframe");

            // Resize the iframes when the window is resized
            $(window).resize(function () {
                $responsive_iframes.each(function () {
                    // Get the parent containe's width and the screen ratio
                    var width = $(this).parent().width();
                    var ratio = $(window).height() / $(window).width();

                    $(this).width(width)
                          .height(width * ratio);
                });
                // Resize to fix all iframes on page load.
            }).resize();
        });
(I also made the jQuery selector look for a class name, rather than all iframes)
Permalink: Simple Responsive IFrame using JavaScript

Visual Studio Shared Project "call is ambiguous"

June 01, 2016

Shared projects are a relatively new thing in Visual Studio, they allow you to share code across multiple assemblies without compiling it in its own dll (the code is compiled into the referencing projects dll). Today I came across a bit of a gotcha - If you reference a shared project in an assembly A and in assembly B, now both of those projects define and export all of the public code from the shared project. Now you have a 3rd project C that also has a reference to the shared project, but also references A and B. You will get a compiler error "call is ambiguous" since the namespace/class/method you are trying to use is now defined 3 times. The simple answer, which is counter intuitive to "normal" library development is to make all of your "shared project" classes "internal" instead of "public". That way each assembly that references the shared project can use the code internally but will not export it to other assemblies.
Permalink: Visual Studio Shared Project "call is ambiguous"

User defined repository injection at runtime

March 01, 2016

A common design pattern is to use a dependency injection container in the composition root to switch between various concrete implementations of an interface abstraction (such as for services, repositories etc.). The configuration for these bindings are often dependant on the build configuration, or an application configuration settings and are singular, as such that only one "concrete implementation" is bound at run time. While recently working on a project, we needed to swap out the implementation of each IRepository based on the user's selection. To put this into context, the application is an ASP.NET MVC 5 website that has some common UI functionality, which we can then plug into multiple different data sources, as per the user's choice of repository. Since we are using Ninject, we can rely on it's ability to bind multiple implementations of an abstraction, by name. We can then use that name (as selected by the user) in a factory method to create instances of each type. Example Ninject module:
using MyProject.ApplicationServices.ExampleData;
using MyProject.Domain.RepositoryDefinitions.ExampleDataRepository;
using Ninject.Modules;

namespace MyProject.UI.MVC.DependencyInjection
{
    public class ExampleDataRepositoryModule : NinjectModule
    {
        public override void Load()
        {
            // define the repo names
            var exampleRepo1Name = "Example Repo 1";
            var exampleRepo2Name = "Example Repo 2";
            var exampleRepo3Name = "Example Repo 3";
            
            // setup all the named versions of the service layers for each of the repository names
            this.Bind<ExampleDataService>().ToSelf().Named(exampleRepo1Name);
            this.Bind<ExampleDataService>().ToSelf().Named(exampleRepo2Name);
            this.Bind<ExampleDataService>().ToSelf().Named(exampleRepo3Name);
            
            // set up the repositories that are bound in each of the above cases
            this.Bind<IExampleDataRepository>().To<Repositories.ExampleRepo1.ExampleDataRepository>().WhenAnyAncestorNamed(exampleRepo1Name);
            this.Bind<IExampleDataRepository>().To<Repositories.ExampleRepo2.ExampleDataRepository>().WhenAnyAncestorNamed(exampleRepo2Name);
            this.Bind<IExampleDataRepository>().To<Repositories.ExampleRepo3.ExampleDataRepository>().WhenAnyAncestorNamed(exampleRepo3Name);
        }
    }
}
We can store the user's selection in some kind of state (in ASP.NET this can be backed by the web session), so we can now use this selection along with the above bindings in a service factory, to create instances of the service with the specified repository.
using MyProject.ApplicationServices.ExampleData;
using MyProject.UI.MVC.Helpers;
using Ninject;

namespace MyProject.UI.MVC.ServiceFactories
{
    public class ExampleDataServiceFactory
    {
        private readonly IKernel ninjectKernel;
        private readonly ISessionHelper sessionHelper;

        public ExampleDataServiceFactory(IKernel ninjectKernel, ISessionHelper sessionHelper)
        {
            this.ninjectKernel = ninjectKernel;
            this.sessionHelper = sessionHelper;
        }

        public ExampleDataService CreateInstance()
        {
            return this.ninjectKernel.Get<ExampleDataService>(this.sessionHelper.CurrentExampleRepoName);
        }
    }
}
Now in the controller, we can take a dependency on the factory and have it create us an instance:
public class ExampleDataController : Controller
    {
        private ExampleDataService exampleDataService;
        private ISessionHelper sessionHelper;

        public ExampleDataController(ExampleDataServiceFactory exampleDataServiceFactory, ISessionHelper sessionHelper)
        {
            this.exampleDataService= exampleDataServiceFactory.CreateInstance();
            this.sessionHelper = sessionHelper;
        }
}
Permalink: User defined repository injection at runtime

StyleCop in VS2015

January 11, 2016

In previous versions of Visual Studio, StyleCop was an msi installation of a VS extension and a global settings file was used to configure the application (StyleCop.settings). In VS2015, with Roslyn and Code Analysis, StyleCop comes as a NuGet package "StyleCop.Analyzers" and it requires two files to configure it (I recommend saving these two files to a common folder and adding the linked files from there in each project). Therefore, in each project:
  • The first step is to install the StyleCop.Analyzers package into the desired projects (or entire solution) using NuGet.
  • File 1: MyRuleset.ruleset - Contains your specific rule customizations
  • File 2: stylecop.json - Configures the StyleCop analyzers process
  • Goto Project > Properties > Code Analysis.. Change the "Rule Set" to "My Ruleset" (for all build configs)
  • Edit the .csproj file, change the item entry from "None/Content" to "AdditionalFiles" e.g.
    <AdditionalFiles Include="..\SharedFolder\SyleCop.Analyzers-VS2015\stylecop.json">
         <Link>stylecop.json</Link>
    </AdditionalFiles>
    
Example contents of the files: MyRuleset.ruleset
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="My Ruleset" Description="My code analysis rules for StyleCop.Analyzer" ToolsVersion="14.0">
  <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
    <Rule Id="SA1600" Action="None" />
    <Rule Id="SA1601" Action="None" />
    <Rule Id="SA1602" Action="None" />
    <Rule Id="SA1633" Action="None" />
    <Rule Id="SA1634" Action="None" />
    <Rule Id="SA1635" Action="None" />
    <Rule Id="SA1636" Action="None" />
    <Rule Id="SA1637" Action="None" />
    <Rule Id="SA1638" Action="None" />
    <Rule Id="SA1640" Action="None" />
    <Rule Id="SA1641" Action="None" />
    <Rule Id="SA1652" Action="None" />
    <Rule Id="SA1118" Action="None" />
    <Rule Id="SA1516" Action="None" />
  </Rules>
</RuleSet>
stylecop.json
{
  "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
  "settings": {
    "documentationRules": {
        "companyName": "PlaceholderCompany"
    },
    "orderingRules": {
        "usingDirectivesPlacement": "outsideNamespace"
    }
  }
}
Permalink: StyleCop in VS2015

Spatial Querying example in CDSA

September 07, 2015

The CDSA architecture templates generate managers and a SQLDAL that is capable of performing any combination of the "normal" queries that you might perform in SQL (such as Equals, Like, In, Less, Greater etc..) However, the default template output does not include any code for performing spatial queries. This is where the extensible nature of CDSA helps us, as we can simply define a new abstraction in the DML for performing a spatial query against the entity that supports it, such as:
public abstract class ExampleGeographyManagerExtns
{
    public abstract Dictionary<Guid, double> GetDataIDsInProximityTo(Guid targetExampleId, double distance);

    public abstract Dictionary<Guid, double> GetDataIDsInProximity(double latitude, double longitude, double distance);

    public abstract List<Guid> GetDataIDsInWKT(string wkt);
}
You can then implement that extension in the SQLDAL as a set of SQL queries:
public class ExampleGeographyManagerExtns : DML.ManagementExtns.ExampleGeographyManagerExtns
{
    private Provider.SqlDataProvider provider;
    private Schemas.SqlExampleGeographySchema schema = Schemas.SqlExampleGeographySchema.GetInstance();

    internal ExampleGeographyManagerExtns(Provider.SqlDataProvider providerInstance)
    {
        this.provider = providerInstance;
    }

    public override Dictionary<Guid, double> GetDataIDsInProximityTo(Guid targetExampleId, double distance)
    {
        // use a sql query to get the averaged data
        string sqlQryText = string.Format(
            @"
SELECT ExampleGeography.ExampleId, ExampleGeography.PointGeography.STDistance(b.PointGeography) Distance
from ExampleGeography
inner join ExampleGeography b
on b.ExampleId=@ExampleId
and b.PointGeography.STBuffer({0}).STIntersects(ExampleGeography.PointGeography)=1
where ExampleGeography.ExampleId<>b.ExampleId
order by Distance asc", distance);

        // create the parameters to the query
        Dictionary<string, object> sqlQryParams = new Dictionary<string, object>();
        sqlQryParams.Add("ExampleId", targetExampleId);

        DataSet rawData = this.provider.SqlHelper.Execute(sqlQryText, CommandType.Text, sqlQryParams);

        Dictionary<Guid, double> results = new Dictionary<Guid, double>();

        if (rawData != null && rawData.Tables.Count > 0)
        {
            foreach (DataRow dr in rawData.Tables[0].Rows)
            {
                results.Add((Guid)dr[this.schema.UniqueId], (double)dr["Distance"]);
            }
        }

        return results;
    }

    public override Dictionary<Guid, double> GetDataIDsInProximity(double latitude, double Longitude, double distance)
    {
        // use a sql query to get the averaged data
        string sqlQryText = string.Format(
            @"
Declare @GeogPoint as geography
Declare @GeogShape as geography

SET @GeogPoint = geography::STGeomFromText('POINT (' + Cast(@longitude as varchar) + ' ' + Cast(@latitude as varchar) + ')', 4326)
SET @GeogShape = @GeogPoint.STBuffer({0})

SELECT ExampleGeography.ExampleId, ExampleGeography.PointGeography.STDistance(@GeogPoint) Distance
from ExampleGeography
where @GeogShape.STIntersects(ExampleGeography.PointGeography)=1
order by Distance asc", distance);

        // create the parameters to the query
        Dictionary<string, object> sqlQryParams = new Dictionary<string, object>();
        sqlQryParams.Add("Latitude", latitude);
        sqlQryParams.Add("Longitude", longitude);

        DataSet rawData = this.provider.SqlHelper.Execute(sqlQryText, CommandType.Text, sqlQryParams);

        Dictionary<Guid, double> results = new Dictionary<Guid, double>();

        if (rawData != null && rawData.Tables.Count > 0)
        {
            foreach (DataRow dr in rawData.Tables[0].Rows)
            {
                results.Add((Guid)dr[this.schema.UniqueId], (double)dr["Distance"]);
            }
        }

        return results;
    }

    public override List<Guid> GetDataIDsInWKT(string wkt)
    {
        string sqlQryText = @"
Declare @GeogPolygon as geography
Declare @GeomPolygon as geometry

Set @GeomPolygon = Geometry::STGeomFromText(@WKT, 4326)
Set @GeogPolygon = Geography::STGeomFromWKB(@GeomPolygon.MakeValid().STUnion(@GeomPolygon.STStartPoint()).STAsBinary(), 4326)

SELECT ExampleGeography.ExampleId
from ExampleGeography
WHERE PointGeography.STIntersects(@GeogPolygon)=1";

        // create the parameters to the query
        Dictionary<string, object> sqlQryParams = new Dictionary<string, object>();
        sqlQryParams.Add("WKT", wkt);

        DataSet rawData = this.provider.SqlHelper.Execute(sqlQryText, CommandType.Text, sqlQryParams);

        List<Guid> results = new List<Guid>();

        if (rawData != null && rawData.Tables.Count > 0)
        {
            foreach (DataRow dr in rawData.Tables[0].Rows)
            {
                results.Add((Guid)dr[this.schema.UniqueId]);
            }
        }

        return results;
    }
}
We can then expose the extension in the IDataProvider interface and SQL implemention:
public partial interface IDataProvider : ClauseWrappers.WhereClauseWrapper.IWhereClauseHandler, ClauseWrappers.OrderByClauseWrapper.IOrderByClauseHandler
{
    // expose specialised management functions/classes
    ManagementExtns.ExampleGeographyManagerExtns ExampleGeographyManagerExtns { get; }
}

public partial class SqlDataProvider : DML.Provider.IDataProvider
{
    private ManagementExtns.ExampleGeographyManagerExtns exampleGeographyManagerExtns;

    public DML.ManagementExtns.ExampleGeographyManagerExtns ExampleGeographyManagerExtns
    {
        get
        {
            if (this.exampleGeographyManagerExtns == null)
            {
                this.exampleGeographyManagerExtns = new ManagementExtns.ExampleGeographyManagerExtns(this);
            }

            return this.exampleGeographyManagerExtns;
        }
    }
}
Finally, we can now expose this functionality through our extended business layer manager class:
public partial class ExampleGeographyManager : BaseClasses.ExampleGeographyManagerBase
{
    public Dictionary<long, double> GetRecordIDsInProximityTo(long targetExampleId, double distance)
    {
        return DataProviders.Current.ExampleGeographyManagerExtns.GetDataIDsInProximityTo(targetExampleId, distance);
    }

    public List<long> GetRecordIDsInWKT(string wkt)
    {
        return DataProviders.Current.ExampleGeographyManagerExtns.GetDataIDsInWKT(wkt);
    }

    public Dictionary<long, double> GetRecordIDsInProximity(double latitude, double longitude, double radiusInMeters)
    {
        return DataProviders.Current.ExampleGeographyManagerExtns.GetDataIDsInProximity(latitude, longitude, radiusInMeters);
    }
}
Permalink: Spatial Querying example in CDSA

Bio - Kinetic

March 02, 2015

I have recently become Solution Architect and Development Lead at Kinetic. My new role extends my responsibilities as a Senior Developer, essentially creating 3 main aspects to my job. Firslty, I continue to do software development where necessary, but also have added responsibilities for the overall architecture of the systems going forward, implementing development strategies and also being a technical lead/consultant for the team and the business. Kinetic Logo
Permalink: Bio - Kinetic