Posts Tagged ‘PSC’

The Results

By:  Cole Francis, Senior Solution Architect, The PSC Group, LLC

Let’s just say that I had a situation where I was calling a third-party API to return valuable information, but that third-party service occasionally failed.  What I discovered through recursion is that 1 out of every 3-5 calls succeeded, but it wasn’t guaranteed.  Therefore, I couldn’t simply wrap my core logic in a hard-coded iterative loop and expect it to succeed.  So, I was relegated to either coming up with a way to write some custom Retry logic to handle errors and reattempt the call or locating and existing third-party package that offers this sort of functionality as not to reinvent the proverbial wheel.

Fortunately, I stumbled across a .NET NuGet Package called Polly.   After reading the abstract about the offering (Click Here to Read More About the Polly Project), I discovered that Polly is a .NET compatible library that complies with transient-fault-handling logic by implementing policies that offer thread-safe resiliency to Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback logic, and in a way that is very easy to implement inside a .NET project codebase.  I also need to point out that Polly targets .NET 4.0, .NET 4.5 and .NET Standard 1.1.

While Polly offers a plethora of capabilities, many of which I’ll keep in my back pocket for a rainy day, I was interested in just one, the Retry logic.  Here’s how I implemented it.  First, I included the Polly NuGet Package in my solution, like so:

The Results

Next, I included the following lines of code when calling the suspect third-party Web API:

// Here is my wait and retry policy, with 250 millisecond wait intervals.
// It will attempt to call the API 10 times.
Policy
  .Handle(e => (e is Exception))
  .WaitAndRetry(10, attempt => TimeSpan.FromMilliseconds(250))
  .Execute(() =>
  {
    // Your core logic should go here!  
    // If an exception is thrown by the called object, 
    // then Polly will wait 250ms and try again for a total of 10 times.
    var response = CallToSuspectThirdPartyAPI(input);
  });

That’s all there really is to it, and I’m only scratching the surface when it comes to Polly’s full gamut of functionality.  Here’s a full list of Polly’s capabilities if you’re interested:

  1. Retry – I just described this one to you.
  2. Circuit Breaker – Fail fast under struggling conditions (you define the conditions and thresholds).
  3. Timeout – Wait until you hit a certain point, and then move on.
  4. Bulkhead Isolation – Provides fault isolation, so that certain failing threads don’t fault the entire process.
  5. Cache – Provides caching (temporary storage and retrieval) capabilities.
  6. Fallback – Anticipates a potential failure and allows a developer to provide an alternative course of action if a potential failure is ever realized.
  7. PolicyWrap – Allows for any (and all) of the previously mentioned policies to be combined, so that different programmatic strategies can be exercised when different faults occur.

Thanks for reading, and keep on coding!  🙂

Advertisements

The Results

Author:  Cole Francis, Senior Solution Architect @ The PSC Group, LLC

Download the Source Code for This Example Here!

BACKGROUND

Traditionally speaking, creating custom Microsoft Windows Services can be a real pain.  The endless and mind-numbing repetitions of using the InstallUtil command-line utility and Ctrl+Alt+P attachments to the debug the code from the Microsoft Visual Studio IDE are more than enough to discourage the average Software Developer.

While many companies are now shying away from writing Windows Services in an attempt to get better optics around job failures, custom Windows Services continue to exist in limited enterprise development situations where certain thresholds of caution are exercised.

But, if you’re ever blessed with the dubious honor of having to write a custom Windows Service, take note of the fact that there are much easier ways of approaching this task than there used to be, and in my opinion one of the easiest ways is to use a NuGet package called TopShelf.

Here are the top three benefits of using TopShelf to create a Windows Service:

  1. The first benefit of using TopShelf is that you get out from underneath the nuances of using the InstallUtil command to install and uninstall your Windows Service.
  2. Secondly, you create your Windows Service using a simple and familiar Console Application template type inside Microsoft Visual Studio.  So, not only is it extraordinarily easy to create, it’s also just as easy to debug and eventually transition into a fully-fledged Windows Service leveraging TopShelf. This involves a small series of steps that I’ll demonstrate for you shortly.
  3. Because you’ve taken the complexity and mystery out of creating, installing, and debugging your Windows Service, you can focus on writing better code.

So, now that I’ve explained some of the benefits of using TopShelf to create a Windows Service, let’s run through a quick step-by-step example of how to get one up and running.  Don’t be alarmed by the number of steps in my example below.  You’ll find that you’ll be able to work through them very quickly.


Step 1

The first step is to create a simple Console Application in Microsoft Visual Studio.  As you can see in the example below, I named mine TopShelfCWS, but you can name yours whatever you want.

The Results


Step 2

The second step is to open the NuGet Package Manager from the Microsoft Visual Studio IDE menu and then click on the Manage NuGet Packages for Solution option in the submenu as shown in the example below.

The Results


Step 3

After the NuGet Package Manager screen appears, click on the Browser option at the top of the dialog box, and then search on the words “TopShelf”.  A number of packages should appear in the list, and you’ll want to select the one shown in the example below.

The Results


Step 4

Next, select the version of the TopShelf product that aligns with your project or you can simply opt to use the default version that was automatically selected for you, which is what I have done in my working example.

Afterwards, click the Install button.  After the package successfully installs itself, you’ll see a green checkbox by the TopShelf icon, just like you see in the example below.

The Results


Step 5

Next, add a new Class to the TopShelfCWS project, and name it something that’s relevant to your solution.  As you can see in the example below, I named my class NameMeAnything.

The Results


Step 6

In your new class (e.g. NameMeAnything), add a reference to the TopShelf product, and then inherit from ServiceControl.

The Results


Step 7

Afterwards, right click on the words ServiceControl and implement its interface as shown in the example below.

The Results


Step 8

After implementing the interface, you’ll see two new events show up in your class.  They’re called Start() and Stop(), and they’re the only two events that the TopShelf product relies upon to communicate with the Windows Service Start and Stop events.

The Results


Step 9

Next, we’ll head back to the Main event inside the Program class of the Console Application.  Inside the Main event, you’ll set the service properties of your impending Windows Service.  It will include properties like:

  • The ServiceName: Indicates the name used by the system to identify this service.
  • The DisplayName: Indicates the friendly name that identifies the service to the user.
  • The Description: Gets or sets the description for the service.

For more information, see the example below.

The Results


Step 10

Let’s go back to your custom class one more time (e.g. NameMeAnything.cs), and add the code in the following example to your class.  You’ll replace this with your own custom code at some point, but following my example will give you a good idea of how things behave.

The Results


Step 11

Make sure you include some Console writes to account for all the event behaviors that will occur when you run it.

The Results


Step 12

As I mentioned earlier, you can run the Console Application simply as that, a Console Application.  You can do this by simply pressing the F5 key.  If you’ve followed my example up to this point, then you should see the output shown in the following example.

The Results


Step 13

Now that you’ve run your solution as a simple Console Application, let’s take the next step and install it as a Window Service.

To do this, open a command prompt and navigate to the bin\Debug folder of your project.   *IMPORTANT:  Make sure you’re running the command prompt in Administrator mode* as shown in the example below.

The Results


Step 14

One of the more beautiful aspects of the TopShelf product is how it abstracts you away from all the .NET InstallUtil nonsense.  Installing your Console Application as a Windows Service is as easy as typing the name of your executable, followed by the word “Install”.  See the example below.

The Results


Step 15

Once it installs, you’ll see the output shown in the example below.

The Results


Step 16

What’s more, if you navigate to the Windows Services dialog box, you should now see your Console Application show up as a fully-operable Windows Service, as depicted below.

The Results


Step 17

You can now modify the properties of your Windows Service and start it.  Since all I’m doing in my example is executing a simple timer operation and logging out console messages, I just kept all the Windows Service properties defaults and started my service.  See the example below.

The Results


Step 18

If all goes well, you’ll see your Windows Service running in the Windows Services dialog box.

The Results


Step 19

So, now that your console application is running as a Windows Service, you’re absent the the advantage of seeing your console messages being written to the console. So, how do you debug it?

The answer is that you can use the more traditional means of attaching a Visual Studio process to your running Windows Service by clicking Ctrl + Alt + P in the Visual Studio IDE, and then selecting the name of your running Windows Service, as shown in the example below.

The Results


Step 20

Next, set a breakpoint on the _timer_Elapsed event.  If everything is running and hooked up properly, then your breakpoint should be hit every second, and you can press F10 to step it though the event handler that’s responsible for writing the output to the console, as shown in the example below.

The Results


Step 21

Once you’re convinced that your Windows Service is behaving properly, you can stop it and test the TopShelf uninstallation process.

Again, TopShelf completely abstracts you away from the nuances of the InstallUtil utility, by allowing you to uninstall your Windows Service just as easily as you initially installed it.

The Results


Step 22

Finally, if you go back into the Windows Services dialog box and refresh your running Windows Services, then you should quickly see that your Windows Service has been successfully removed.

The Results


SUMMARY

In summary, I walked you through the easy steps of creating a custom Windows Service using the TopShelf NuGet package and a simple C# .NET Console application.

In the end, starting out with a TopShelf NuGet package and a simple Console application allows for a much easier and intuitive Windows Service development process, because it abstracts away all the complexities normally associated with traditional Windows Service development and debugging, resulting in more time to focus on writing better code. These are all good things!

Hi, I’m Cole Francis, a Senior Solution Architect for The PSC Group, LLC located in Schaumburg, IL.  We’re a Microsoft Partner that specializes in technology solutions that help our clients achieve their strategic business objectives.  PSC serves clients nationwide from Chicago and Kansas City.

Thanks for reading, and keep on coding!  🙂

CreateImagefromPDF

By: Cole Francis, Senior Architect at The PSC Group, LLC.

Let’s say you’re working on a hypothetical project, and you run across a requirement for creating an image from the first page of a client-provided PDF document.  Let’s say the PDF document is named MyPDF.pdf, and your client wants you to produce a .PNG image output file named MyPDF.png.

Furthermore, the client states that you absolutely cannot read the contents of the PDF file, and you’ll only know if you’re successful if you can read the output that your code generates inside the image file.  So, that’s it, those are the only requirements.   What do you do?

SOLUTION

Thankfully, there are a number of solutions to address this problem, and I’m going to use a lesser known .NET NuGet package to handle this problem.  Why?  Well, for one I want to demonstrate what an easy problem this is to solve.  So, I’ll start off by searching in the .NET NuGet Package Manager Library for something describing what I want to do.  Voila, I run across a lesser known package named “Pdf2Png”.  I install it in less than 5 seconds.

Pdf2Png.png

So, is the Pdf2Png package thread-safe and server-side compliant?  I don’t know, but I’m not concerned about it because it wasn’t listed as a functional requirement.  So, this is something that will show up as an assumption in the Statement-of-Work document and will be quickly addressed if my assumption is incorrect.

Next, I create a very simple console application, although this could be just about any .NET file type, as long as it has rights to the file system.  The process to create the console application takes me another 10 seconds.

Next, I drop in the following three lines of code and execute the application, taking another 5 secondsThis would actually be one line of code if I was passing in the source and target file locations and names.

 string pdf_filename = @"c:\cole\PdfToPng\MyPDF.pdf";
 string png_filename = @"c:\cole\PdfToPng\MyPDF.png";
 List errors = cs_pdf_to_image.Pdf2Image.Convert(pdf_filename, png_filename);

Although my work isn’t overwhelmingly complex, the output is extraordinary for a mere 20 seconds worth of work!  Alas, I have not one, but two files in my source folder.  One’s my source PDF document, and the other one’s the image that was produced from my console application using the Pdf2Png package.

TwoFiles.png

Finally, when I open the .PNG image file, it reveals the mysterious content that was originally inside the source PDF document:

SomeThingsArentHard.png

Before I end, I have to mention that the Pdf2Png component is not only simple, but it’s also somewhat sophisticated.  The library is a subset of Mark Redman’s work on PDFConvert using Ghostscript gsdll32.dll, and it automatically makes the Ghostscript gsdll32 accessible on a client machine that may not have it physically installed.

Thanks for reading, and keep on coding!  🙂

AngularJS SPA

By:  Cole Francis, Senior Solution Architect at The PSC Group, LLC.

PROBLEM

There’s a familiar theme running around on the Internet right now about certain problems associated with generating SEO-friendly Sitemaps for SPA-based AngularJS web applications.  They often have two funamental issues associated with their poor architectural design:

  1. There’s usually a nasty hashtag (#) or hashbang (#!) buried in the middle of the URL route, which the website ultimately relies upon for parsing purposes in order to construct the real URL route (e.g. https://www.myInheritedWebApp.com/stuff/#/items/2
  2. Because of the embedded hashtag or hashbang, the URL’s are dynamically constructed and don’t actually point to content without parsing the hashtag (or hashbang) operator first.  The underlying problem is that a Sitemap.xml document can’t be auto-generated for SEO indexing.

I realize that some people might be offended by my comment about “poor achitectural design”.  I state this loosely, because it’s really just the nature of the beast.  Why?  Because it’s really easy to get started with AngularJS, and many Software Developers simply start laying down code that’s initially decent, but at some point they start implementing hacks because of added complexity to the original functional requirements.  That’s where they begin to get themselves in trouble very creative. 🙂

If you think I’m kidding, then just try Googling the following keywords and you’ll see exactly what I mean:  AngularJS, hash, hashbang, SEO, Sitemap, problem.

SOLUTION

So, the first step is to remove the hashtag (#) or the hashbang (#!).  I know it sucks, and it’s going to require some work, but let me be clear.  Do it!  For one, generating the Sitemap will be much easier, because you won’t need to parse on a hashtag (or hashbang) to get the real URL.  Secondly, all the remediation work you do will be a reminder the next time you think about taking shortcuts.

Regardless, after correcting the hashtag problem, you still have another issue.  Your website is still an AngularJS SPA-based website, which means that all its content is dynamically generated and injected through JavaScript AJAX calls.

Given this, how will you ever be able to generate a Sitemap containing all your content (e.g. products, catalogs, people, etc…)? Even more concerning, how will people find your people or products when searching on Google?

Luckily, the answer is very simple.  Here’s a little gem that I recently ran across while trying to generate a Sitemap.xml document on an AngularJS SPA architected website, and it works like a charm:  http://botmap.io/

I literally copied the script on the BotMap website to the bottom of my shared\_Layout.cshtml file, just above the closing tag.  This gives BotMap permission to crawl your website.  After doing this, push your website to Production, then point the BotMap website to your publicly-facing URL, and finally click the button on their website to initiate the crawl.  One and done!

BotMap begins to crawl and catalog your website as if it was a real person browsing it. It doesn’t use CURL or xHttp requests to determine what to catalog. The BotMap crawler actually executes the JavaScript, which is how it ultimately learns about all of the content on your website that it will use to construct the Sitemap.  

This is why it’s so great for websites created using AngularJS or other JavaScript frameworks where content is injected inside the JavaScript code itself.  Congratulations, {{vm.youreDone}}!

Thanks for reading, and keep on coding!  🙂

My First Azure Function

Posted: July 6, 2017 in Azure, Azure Functions, Cloud
Tags:

Main

BACKGROUND

Azure functions are an ideal way to write discrete pieces of code in the cloud without concerning yourself with the machine and infrastructure that will support them.  Azure functions also offer a variety of different development language choices, including C#, Python, PHP, Node.js, and F#.

Furthermore, Azure functions are able to run inside the Azure Compute Stack’s “Consumption Hosting Plan”, which means that you only get charged for the amount of time the code executes.  They also support NuGet and NPM Package Management, so you still have access to all of your favorite templates and libraries.  

Additionally, they come with integrated security, so OAuth providers, such as Azure AD, Microsoft Account, Facebook, Google, and Twitter are readily available.

Moreover, you can easily integrate with Azure services and SaaS offerings, including Azure Cosmos DB, Azure Event Hubs, Azure Mobile Apps (tables), Azure Notification Hubs, Azure Service Bus, Azure Storage, GitHub (through webhooks),  on-prem (using Service Bus), Twilio (SMS messages).

In addition to this, you can code your functions right inside the Azure portal, which I’ll do in my example, and you can even setup continuous integration and deploy your code through VSTS and GitHub (and others).

In the following step-by-step example, I’ll create my very first Azure function.  If you’re new to this like I am, then perhaps you can create your very first Azure function together with me?  In any case, here we go…

STEP 1

The first step is to login to your Microsoft Azure Portal account.  Once you’ve successfully done this, then click “New” on the left navigation bar.

Step1

STEP 2

When the “New” menu pops up, click on the “Compute” option in the list.

Step 2

STEP 3

Once you click on the “Compute” item in the Marketplace selections, look for the “Function App” option in the Compute item list.

Step3

STEP 4

A new “Function App” creation dialogue box will ask you to name your application.  I called mine functions-cfrancis2017.  You can name your whatever you like.  

Also, keep the “Consumption Plan” selected as the “Hosting Plan”.  Azure provides two types of pricing in this category, including the Consumption Plan and the App Service Plan.  Here’s the difference between the two:

  • Consumption plan – When your function runs, Azure provides all of the necessary computational resources. You don’t have to worry about resource management, and you only pay for the time that your code runs.
  • App Service plan – Run your functions just like your web, mobile, and API apps. When you are already using App Service for your other applications, you can run your functions on the same plan at no additional cost.

Step4

STEP 5

Once you’re satisfied with the name of your “Function App”, then click the Create button at the bottom of the dialogue box.

Step5

STEP 6

You should now be able to find your new App Service and Storage Account in the Azure Portal.

Step6.png

STEP 7

Clicking on your function allow you to inspect its details.  You can even toggle your new Function App as a favorite by clicking on the star next to your new function.

Step7

STEP 8

Once you toggle it as your favorite, you can easily find it anytime you look through the Function Apps section of the Azure Portal.

Step8

STEP 9

Click on the following items to display more information about your new Function App or to drill down on the type of item you’d like to create under this category.

Step9

STEP 10

We want to create a new Azure Function that lives in our new Function App.  So, just:

  1. click on (+) next to the “Function” item.
  2. Choose the scenario you want.  I chose a “Webhook + API”
  3. Click on the “Create this function” button.

Step11

STEP 11

After you click on the “Create this function” in the previous example, the following code block will automatically display in the language you chose.  I chose JavaScript as my Webhook.

Step12

STEP 12

Click the “Run” button just to try it out.  Once you’re satisfied with the results, try running the Azure Function remotely.

Step13

STEP 13

To run it remotely, click on the “</> Get function URL” selection to bring up the Azure Function URL.  This is the restful service you will call to execute your new Azure Function.

Step14

STEP 14

Select the default (Function key) and review the results of the HTTP(S) call.

Step15

STEP 15

Do the following:

  1. Paste the link you just copied into a mainstream browser of your choice.
  2. Click the “Enter” key to navigate to the URL.
  3. Review the results.  They’re perfect!

Step16

STEP 16

Now you can go back into the Azure Portal and review the results for the calls that you (or anyone else) makes to your new Azure Function.

Step17

SUMMARY

From a primitive standpoint, that’s all there is to it.  Of course, I’ll provide a more complex implementation of one in a future article.

Hi, I’m Cole Francis, a Solution Architect for The PSC Group in Schaumburg, IL. I’ve been successfully designing, developing, and delivering custom software solutions for an impressive and extensive list of well-branded clients for over twenty years.

Thanks for reading and keep on coding! 😁

SQL Server Spatial

Author:  Cole Francis, Architect

THE PROBLEM

So, wrap your head around this for a minute.  Let’s suppose that you’re a small company that sells casualty insurance to property owners in South Florida.

Your business is thriving, but you feel like you’ve completely saturated the market in that region, so now you want to expand your offerings to a small territory in central Florida.

After conducting rigorous research on the demographic data, you realize that hurricane insurance along the central-east coast is white hot right now.  You conclude that this is the result of booming home turnovers within that area.

The demographic area that your team has decided to pursue starts at West Palm Beach and extends all the way down to Miami.  What’s more, most of the activity in the area appears to be occurring between the coast and 10 miles inland.

So, you assemble your Sales and Marketing Team, and you provide them with the results of your fact finding.  Then you ask them to formulate a strategy that will allow the company to maximize their insurance sales efforts within that area.

Days later, the team reassembles and tells you what they found out about the area.  It turns out they recommend targeting a small territory of homes, which have recently sold along the A1A in West Palm Beach along Ocean Blvd, suffering from sudden turnover.

The team also explains that the sudden turnover is predominantly due to a large concentration of aging homeowners in the area that are selling their large homes and are opting for smaller living arrangements.

Much to everyone’s glee, the area also comes with a strong per capita household income, has a low crime rate, and has an average occurrence of natural disasters.

The entire team is excited about pursuing the new region per the demographic data, so their next step is to carefully map out the latitude/longitude coordinates of the area using their favorite mapping website.  Here are the coordinates they’ve used to construct their target market area.  Do you notice how they form a nice little polygon?

A1A

Next, you march down to the Palm Beach County Clerk’s Office and request an Excel Spreadsheet containing the addresses and latitude/longitude coordinates for all new and existing homes sales in the area for the past ninety days.

Of course, the spreadsheet the county offers lists far more addresses and geocoordinates than the small demographic region that your business is targeting.

Therefore, it’s up to your company to pare down the county’s results to only include addresses that are inside your target demographic polygon.  Realizing the manual complexity of this effort, you hand the data and other project artifacts over to your technical team to figure out.

Regardless, in most cases you can easily tell if a home’s latitude/longitude coordinates are well within the acceptable range by just visually inspecting them.

To this point, what I’m showing you in the picture below are the coordinates of those homes that are on the fringe of acceptability, meaning we can’t easily tell if the residences are inside or outside our target demographic polygon using a simple visual inspection.

Given this, you’ll need a quick way to process this data and pare the results down to only those households that the Sales and Marketing Team wants to pursue in the defined area.  So, how can you do this?

Well, you can either manually check them in Google Maps, but this would mean that you either have a really small set of data or a whole lot of time on your hands.  😁

Or, you can try a more automated approach using a platform like SQL Server.  Why SQL Server you ask?  The answer really lies in that there are two spatial data types in SQL Server that can help us quickly solve this problem.  The data types are called Geography and Geometry.

It’s important that you understand the difference between these two data type objects, including what they are and how they are used, because they’re similar but definitely not the same.

THE GEOGRAPHY DATATYPE

Although the geography data type sounds like the right fit for what we’re about to accomplish, it actually compounds the problem.  This is because the Geography data type is used for terrestrial spatial data covering the convex surface of the Earth.

Because of its ellipsoidal nature, any polygons that you use to define an area cannot exceed a single hemisphere and must specify the correct ring orientation.

It’s for these very reasons that simply drawing a polygon somewhere on its surface doesn’t give you enough information to make accurate determinations about geocoordinates that get fed into it.

For instance, if I were to draw an area around the Equator of the globe, and then I were to ask you if a specific latitude/longitude coordinate fell inside or outside the boundary I just drew, you wouldn’t have enough information to answer my question.

Why you might ask?  It’s because you would have to know if I was targeting the northern or southern ring of the Equator, the western or eastern hemisphere, and whether the polygon I constructed was meant to include or exclude the target latitude/longitude coordinates.

THE GEOMETRY DATATYPE

When I think of the SQL Server geometry data type and apply it to this problem, one of the first things that comes to my mind is a 1991 book, “Inventing the Flat Earth”, written by retired University of California Professor, Jeffrey Burton Russell.  In the book, Russell discusses how the “flat Earth” myth was disseminated by early 19th century writers like Antoinne-Jean Letronne, and others of course.

In the case of this data type, Microsoft SQL Server takes an opposite viewpoint of Russell.   Instead, they provide a geometry data type that allows us to construct the problem and solution using what you might think of as a “steroidal planar Earth object”, which conforms to the Open Geospatial Consortium (OGC).

I actually coined the term “Steroidal Flat Earth Object”, because the object’s range extends far beyond the -90 to 90 latitudes and -180 to 180 longitude maximums defining the Earth’s geographic range.

Because it’s just a very large, single-dimension plane, it’s not necessary to define if the target coordinates lie to the West or East of the Prime Meridian when using this data type.

However, there are still some basic rules that need to be followed in order to construct a well-formed polygon.  One is that the sequence order in which the vertices get added is important, just as I mentioned earlier in this article.  If you get the sequence wrong, then your polygon could have issues like the example shown below.

PolygonVertices

The other important rule is that you must make sure that your final coordinate is equal to your first coordinate in order to officially close the loop on your polygon.  If you don’t close the loop on the polygon, then SQL Server throws an error when you try to execute the code.

But, once you get things right, the result is a built-in SQL Server math function that offers an accurate determination on whether a point (i.e. a single coordinate) or a line (i.e. one or more coordinates) intersects or lies inside the perimeter of a well-defined polygon.

Pretty nifty, huh?  So, here’s the solution…

THE SOLUTION (COPY & PASTE THIS INTO SQL SERVER, AND THEN RUN IT)

--create a variable table
declare @coordinates table
(
id int identity (1,1),
coordinate geometry
)
declare @recordCount as int

-- @area represents the demographic area
-- *note: The sequence in how you add each point to construct
-- the polygon is very important.
declare @area as geometry

--turn off the verbose SQL Server logging
set nocount on

-- enter the fringe lat/long County coordinates into the table (this process would normally be automated).
insert into @coordinates (coordinate)
select geometry::Point(26.688379,-80.034762,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.684662,-80.037804,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.679250,-80.035808,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.674490,-80.037095,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.675722,-80.039778,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.700533,-80.034413,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.675402,-80.036230,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.694902,-80.037331,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.692697,-80.039852,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.693809,-80.041225,4326)
insert into @coordinates (coordinate)
select geometry::Point(26.677084,-80.037010,4326)

-- set up the demographic area by constructing a polygon of coordinates.-- *note: the final coordinate MUST match the first coordinate in order-- to close the polygon.  If it’s left open, then it won’t work.
-- *note: the sequence of the coordinates used to construct the polygon is also important.
set @area = geometry::STGeomFromText('POLYGON(( 26.697583 -80.033367, 26.691103 -80.033635, 26.681781 -80.035083, 26.679250 -80.035094, 26.679116 -80.035287, 26.674653 -80.035791, 26.672870 -80.035952, 26.668939 -80.035920, 26.668498 -80.035748, 26.665876 -80.036177, 26.664601 -80.036467, 26.661456 -80.036467, 26.661101 -80.038184, 26.661417 -80.038431, 26.663517 -80.038420, 26.665228 -80.038855, 26.665391 -80.038791, 26.666254 -80.038855, 26.666340 -80.038764, 26.666891 -80.038764, 26.667706 -80.038657, 26.669571 -80.038802, 26.670300 -80.038684, 26.670923 -80.039001, 26.671575 -80.039108, 26.671652 -80.039044, 26.673430 -80.039151, 26.673507 -80.039516, 26.675731 -80.039773, 26.683496 -80.038325, 26.686564 -80.037338, 26.687676 -80.037005, 26.689516 -80.037048, 26.691011 -80.037863, 26.692219 -80.039322, 26.692161 -80.040084, 26.693081 -80.040041, 26.693110 -80.038957, 26.694452 -80.038914, 26.694682 -80.038807, 26.694720 -80.040910, 26.694375 -80.041125, 26.694394 -80.042058, 26.697583 -80.033367))', 4326)

select @recordCount = count(id) FROM @coordinates
while (@recordCount > 0)
begin 
     declare @forwardPoint geometry 
     declare @identity int 
     select Top(1) @identity=id, @forwardPoint=coordinate from @coordinates 
     set @forwardPoint = @forwardPoint.MakeValid();

     if (@forwardPoint.STIntersection(@area).ToString() <> 'GEOMETRYCOLLECTION EMPTY') and (@forwardPoint.STIntersection(@area).ToString() <> 'GEOMETRYCOLLECTION EMPTY') 
     begin 
          print 'Id ' + cast(@recordCount as varchar(10)) + ' is inside the target demographic area for lat/lng ' + cast(@forwardPoint as varchar(100)) 
     end 
     else 
     begin 
          print 'Id ' + cast(@recordCount as varchar(10)) + ' is outside the target demographic area for lat/lng ' + cast(@forwardPoint as varchar(100)) 
     end
     
     delete from @coordinates where id = @identity select @recordCount = count(id) FROM @coordinates
 end

-- turn verbose logging back on
set nocount on


THE END RESULT IS THIS

The Sales Team will now pursue every household (represented as a lat/lng coordinate below) that falls inside the target demographic area.  Coordinates that fall outside the target area will be ignored by the Sales Team for now:

Id 11 is inside the target demographic area for lat/lng POINT (26.688379 -80.034762)
Id 10 is inside the target demographic area for lat/lng POINT (26.684662 -80.037804)
Id 9 is inside the target demographic area for lat/lng POINT (26.67925 -80.035808)
Id 8 is inside the target demographic area for lat/lng POINT (26.67449 -80.037095)
Id 7 is outside the target demographic area for lat/lng POINT (26.675722 -80.039778)
Id 6 is outside the target demographic area for lat/lng POINT (26.700533 -80.034413)
Id 5 is inside the target demographic area for lat/lng POINT (26.675402 -80.03623)
Id 4 is inside the target demographic area for lat/lng POINT (26.694902 -80.037331)
Id 3 is inside the target demographic area for lat/lng POINT (26.692697 -80.039852)
Id 2 is outside the target demographic area for lat/lng POINT (26.693809 -80.041225)
Id 1 is inside the target demographic area for lat/lng POINT (26.677084 -80.03701)

For more information on Microsoft SQL Server Spatial Data Types, click here.

Hi, I’m Cole Francis, a Solution Architect for The PSC Group in Schaumburg, IL.  I’ve been successfully designing, developing, and delivering custom software solutions for an impressive and extensive list of well-branded clients for over twenty years.

Thanks for reading and keep on coding! 🙂

XFactor

By: Cole Francis, Architect, PSC, LLC


THE PROBLEM

So, what do you do when you’re building a website, and you have a long-running client-side call to a Web API layer. Naturally, you’re going to do what most developers do and call the Web API asynchronously.  This way, your code can continue to cruise along until a result finally return from the server.

But, what if matters are actually worse than that?  What if your Web API Controller code contacts a Repository POCO that then calls a stored procedure through the Entity Framework.  And, what if the Entity Framework leverages a project dedicated database, as well as a system-of-record database, and calls to your system-of-record database sporadically fail?

Like most software developers, you would lean towards looking at the log files, offering traceability and logging for your code.  But, what if there wasn’t any logging baked into the code?  Even worse, what if this problem only occurred sporadically?  And, when it occurs, orders don’t make it into the system-of-record database, which means that things like order changes and financial transactions don’t occur.  Have you ever been in a situation like this one?


PART I – HERE COMES ELMAH

From a programmatic perspective, let’s hypothetically assume that the initial code had the controller code calling the repository POCO in a simple For/Next loop that iterates a hardcoded 10 times.  So, if just one of the 10 iterating attempts succeeds, then it means that the order was successfully processed.  In this case, the processing thread would break free from the critical section in the For/Next loop and continue down its normal processing path.  This, my fellow readers, is what’s commonly referred to as “Optimistic Programming”.

The term, “Optimistic Programming”, hangs itself on the notion that your code will always be bug-free and operate on a normal execution path.  It’s this type of programming that provides a developer with an artificial comfort level.  After all, at least one of the 10 iterative calls will surely succeed.  Right?  Um…right?  Well, not exactly.

Jack Ganssle, from the Ganssle Group, does an excellent job explaining why this development approach can often lead to catastrophic consequences.  He does this in his 2008 online rant entitled, “Optimistic Programming“.  Sure, his article is practically ten years old at this point, but his message continues to be relevant to this very day.

The bottom line is that without knowing all of the possible failure points, their potential root cause, and all the alternative execution paths a thread can tread down if an exception occurs, then you’re probably setting yourself up for failure.  I mean, are 10 attempts really any better than one?  Are 10,000 calls really any better than 10?  Not only are these flimsy hypothesis with little or no real evidence to back them up, but they further convolute and mask the underlying root cause of practically any issue that arises.  The real question is, “Why are 10 attempts necessary when only one should suffice?”

So, what do you do in a situation when you have very little traceability into an ailing application in Production, but you need to know what’s going on with it…like yesterday!  Well, the first thing you do is place a phone call to The PSC Group, headquartered in Schaumburg, IL.  The second thing you do is ask for the help of Blago Stephanov, known internally to our organization as “The X-Factor”, and for a very good reason.  This guy is great at his craft and can accelerate the speed of development and problem solving by at least a factor 2…that’s no joke.

In this situation, Blago recommends using a platform like Elmah for logging and tracing unhandled errors.  Elmah is a droppable, pluggable logging framework that dynamically captures all unhandled exceptions.  It also offers color-coded stack traces with line numbers that can help pinpoint exactly where the exception was thrown.  Even more impressive, its very quick to implement and requires low personal involvement during integration and setup.  In a nutshell, its implementation is quick and it makes debugging a breeze.

Additionally, Elmah comes with a web page that allows you to remotely view the unhandled exceptions.  This is a fantastic function for determining the various paths, both normal and alternate, that lead up to an unhandled error. Elmah also allows developers to manually record their own information by using the following syntax.

ErrorSignal.FromCurrentContext().Raise(ex);

 

Regardless, Elmah’s capabilities go well beyond just recording exceptions. For all practical purposes, you can record just about any information you desire. If you want to know more about Elmah, then you can read up on it by clicking here.  Also, you’ll be happy to know that you can buy if for the low, low price of…free.  It just doesn’t get much better than this.


PART II – ONE REALLY COOL (AND EXTREMELY RELIABLE) RE-TRY PATTERN

So, after implementing Elmah, let’s say that we’re able to track down the offending lines of code, and in this case the code was failing in a critical section that iterates 10 times before succeeding or failing silently.  We would have been very hard-pressed to find it without the assistance of Elmah.

Let’s also assume that the underlying cause is that the code was experiencing deadlocks in the Entity Framework’s generated classes whenever order updates to the system-of-record database occur.  So, thanks to Elmah, at this point we finally have some decent information to build upon.  Elmah provides us with the stack trace information where the error occurred, which means that we would be able to trace the exception back to the offending line(s) of code.

After we do this, Blago recommends that we craft a better approach in the critical section of the code.  This approach provides more granular control over any programmatic retries if a deadlock occurs.  So, how is this better you might ask?  Well, keep in mind from your earlier reading that the code was simply looping 10 times in a For/Next loop.  So, by implementing his recommended approach, we’ll have the ability to not only control the number of iterative reattempts, but we can also control wait times in between reattempted calls, as well as the ability to log any meaningful exceptions if they occur.

 

       /// <summary>
       /// Places orders in a system-of-record DB
       /// </summary>
       /// <returns>An http response object</returns>
       [HttpGet]
       public IHttpActionResult PlaceOrder()
       {
           using (var or = new OrderRepository())
           {
               Retry.DoVoid(() => or.PlaceTheOrder(orderId));
               return Ok();
           }
       }

 

The above Retry.DoVoid() method calls into the following generic logic, which performs its job flawlessly.  What’s more, you can see in the example below where Elmah is being leveraged to log any exceptions that we might encounter.

 

using Elmah;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PSC.utility
{
   /// <summary>
   /// Provides reliable and traceable retry logic
   /// </summary>
   public static class Retry
   {
       /// <summary>
       /// Retry logic
       /// </summary>
       /// <returns>Fire and forget</returns>
       public static void DoVoid(Action action, int retryIntervallInMS = 300, int retryCount = 5)
       {
           Do<object>(() =>
           {
               action();
               return null;
           }, retryIntervallInMS, retryCount);
       }

       public static T Do<T>(Func<T> action, int retryIntervallInMS = 300, int retryCount = 5)
       {
           var exceptions = new List<Exception>();
           TimeSpan retryInterval = TimeSpan.FromMilliseconds(retryIntervallInMS);

           for (int retry = 0; retry < retryCount; retry++)
           {
               bool success = true;

               try
               {
                   success = true;

                   if (retry > 0)
                   {
                       Thread.Sleep(retryInterval);
                   }
                   return action();
               }
               catch (Exception ex)
               {
                   success = false;
                   exceptions.Add(ex);
                   ErrorSignal.FromCurrentContext().Raise(ex);
               }
               finally
               {
                   if (retry > 0 && success) {
                       ErrorSignal.FromCurrentContext().Raise(new Exception(string.Format("The call was attempted {0} times. It finally succeeded.", retry)));
                   }
               }
           }
           throw new AggregateException(exceptions);
     }
   }
}

As you can see, the aforementioned Retry() pattern offers a much more methodical and reliable approach to invoke retry actions in situations where our code might be failing a few times before actually succeeding.  But, even if the logic succeeds, we still have to ask ourselves questions like, “Why isn’t one call enough?” and “Why are we still dealing with the odds of success?”

After all, not only do we have absolutely no verifiable proof that looping and reattempting 10 times achieves the necessary “odds of success”.  Therefore, the real question is why there should there be any speculation at all in this matter?  After all, we’re talking about pushing orders into a system-of-record database for revenue purposes, and the ability to process orders shouldn’t boil down to “odds of success”.  It should just work…every time!

Nonetheless, what this approach will buy us is one very valuable thing, and that’s enough time to track down the issue’s root cause.  So, with this approach in place, our number one focus would now be to find and solve the core problem.


PART III – PROBLEM SOLVED

So, at this point we’ve relegated ourselves to the fact that, although the aforementioned retry logic doesn’t hurt a thing,  it masks the core problem.

Blago recommends that the next step is to load test the failing method by creating a large pool of concurrent users (e.g. 1,000) all simulating the order update function at the exact same time.  I’ll also take it one step further by recommending that we also need to begin analyzing and profiling the SQL Server stored procedures that are being called by the Entity Framework and rejected.

I recommend that we first review the execution plans of the failing stored procedures, making sure their compiled execution plans aren’t lopsided.  if we happen to notice that too much time is being spent on individual tasks inside the stored procedure’s execution plan, then our goal should be to optimize them.  Ideally, what we want to see is an even distribution of time optimally spread across the various execution paths inside our stored procedures.

In our hypothetical example, we’ll assume there are a couple of SQL Server tables using complex keys to comprise a unique record on the Order table.

Let’s also assume that during the ordering process, there’s a query that leverages the secondary key to retrieve additional data before sending the order along to the system-of-record database.   However, because the complex keys are uniquely clustered, getting the data back out of the table using a single column proves to be too much of a strain for the growing table.  Ultimately, this leads to query timeouts and deadlocks, particularly under load.

To this end, optimizing the offending stored procedures by creating a non-clustered, non-unique index for the key attributes in the offending tables will vastly improve their efficiency.  Once the SQL optimizations are complete, the next step should be to perform more load tests and to leverage the SQL Server Profiling Tool to gauge the impact of our changes.  At this point, the deadlocks should disappear completely.


LET’S SUMMARIZE, SHALL WE

The moral of this story is really twofold.  (1) Everyone should have an “X-Factor” on their project; (2) You can’t beat great code traceability and logging in a solution. If option (1) isn’t possible, then at a minimum make sure that you implement option (2).

Ultimately, logging and traceability help out immeasurably on a project, particularly where root cause analysis is imperative to track down unhandled exceptions and other issues.  It’s through the introduction of Elmah that we were able to quickly identify and resolve the enigmatic database deadlock problems that plagued our hypothetical solution.

Regardless, while this particular scenario is completely conjectural, situations like these aren’t all that uncommon to run across in the field.  Regardless, most of this could have been prevented by following Jack Ganssule’s 10-year old advice, which is to make sure that you check those goesintas and goesoutas!  But, chances are that you probably won’t.

Thanks for reading and keep on coding! 🙂