Tuesday, December 25, 2018

Saving Data to Various Formats, Using SQL

I enjoy pulling the data out of AdventureWorks. It is a great test harness. What is the quickest way of doing it? Well, everyone knows it is native BCP, but how much faster is that format than tab-delimited or comma-delimited BCP? Can we quickly output data in XML? Is there a way of outputting array-in-array JSON reasonably quickly? Of course, the answer is going to vary from system to system, and across versions, but any data about this is usually welcome.

In addition to these questions, I wanted to know more about how much space these files take up, either raw or zipped. We’re about to find out. We’ll test all that, using good ol’ BCP and SQLCMD.

My motivation for doing this was to explore ways of quickly transferring data to MongoDB. to test out a way of producing array-in-array JSON at a respectable turn of speed. It turned out to be tricky. The easy and obvious ways were slow.

How? Why?

The reason I like AdventureWorks is that it has a bit of an assault course there. There are illegal column names, reserved words used as columns, CLR types, and free text search. Not as much of this as I’d like, of course, but it makes things a bit more tricky, so it is good for testing, along with old Pubs with its awkward obsolete data types.

Because the SQL Server implementation of XML and JSON are rather delicate creatures that quail at the smell of a CLR Datatype, or a column name with an embedded space, we generally need some supporting logic, rather than belt out the tables to file just by SELECT *.

As most people know, you can use BCP very simply, just specifying each table. Here we output in Tab-delimited format in utf-8, which is a format that Excel likes. It is safe as long as you don’t include tab characters in your spreadsheet cells! Note that xp_cmdshell must be enabled to try this example.

--over-ride this path if you need to.
DECLARE @ourPath sysname = 'OurPath\TabDelimited\';
DECLARE @Database sysname = Db_Name(); 
DECLARE @command NVARCHAR(4000)= '
EXECUTE xp_cmdshell ''bcp  ?  out '+@ourPath +'?.Tab -c -C 65001 -d'
    +@Database+' -T -S '+@@servername +''', NO_OUTPUT;'
EXECUTE sp_msforeachtable @command

Native and “comedy-limited” formats aren’t much harder. Proper CSV format output from the tables of a database is only possible via ODBC.

Creating the Test Harness

For this task, I set up several directories on the server for the different types of output

Then ran the script from The Code section in this article which wrote out the data from AdventureWorks into each directory in the different formats. I included within the batch all the necessary temporary procedures along with a routine that switched in the configuration that allowed me to use xp_cmdshell and then switched it off again.

Into each directory was written all the files, one for each table, like this.

One can, and should of course, open these files up and check on them. Here is the Tab-delimited format.

OK, it would be good not to have the quoted identifiers in the filename [Human Resources]. [Employee].Tab, perhaps, but they are legal. If they irritate you, it is very quick and easy to remove them.

Get-ChildItem -path 'MyDirectory’ -Filter "*.*" -Recurse |
  foreach{if ($_.name -match '(\[|\])')
      { Rename-Item -NewName {$_.name -replace '(\[|\])',''}}}

Mixed Usefulness of the Different Formats

Not all these formats are particularly useful. Tab-delimited is fine just so long as you don’t have tabs in any strings. The comma-separated format isn’t CSV. If you run …

SQLCMD -d AdventureWorks2016 -E -u  -s, -W -Q "set nocount on; SELECT * from (values ('This text has commas, like this, and so should be delimited.','comedy-limited, nice but unreliable'),(',,,,,','This text has no commas'))f(one,two)"

… you will see instantly that it hasn’t coped. It isn’t CSV.

one,two

—,—

This text has commas, like this, and so should be delimited.,comedy-limited, nice but unreliable

,,,,,,This text has no commas

The Results

The XML via BCP and the native BCP both worked very rapidly. Tab delimited and comma-delimited took a little bit longer. SQLCMD and the object-in-array JSON were slightly laggard but respectable. Bringing up the rear was the array-in-array-format. I originally tried exporting array-in-array JSON via XML. However, it turned out to be too slow. Although XML is quick to export, the overhead of converting it to JSON is slow. The method of using OpenJSON was again prohibitively slow, taking two or three minutes.

A word of caution with these results. They can vary considerably, even on the same server and general setup.

The performance of array-in-array JSON was as good as I can manage to get. CLR, or even PowerShell could easily do better. I’d prefer to wait for SQL Server to support the format. However, this is only five times as long as the fastest, BCP. It is usable for most purposes.

What about the space they take up?

The advantage of the array-in-array format of JSON is that the text takes half the space of the object -in-array format. This advantage almost vanishes when the files are zipped, though.

XML and Json Object-in-Array format both take around twice as much space as the simpler tabular formats, which is unsurprising as they are more versatile in the structure of the information they can hold. The large space used by comma-delimited files is due to the fact that I had difficulty storing the file in UTF-8 format. I opted for Unicode instead. This disappeared when the files were zipped. Comma-delimited format was only there for the sake of completion.

All the formats, when zipped, take roughly the same space. This shouldn’t be a surprise because they all held exactly the same information. It is just that some formats repeated it a lot!

The Code

So, here is the SQL to run the comparative tests. They take some time to run. Something like three and a half minutes for AdventureWorks. You’ll see that we start by hurriedly ensuring that we are allowed to use XP_CmdShell and changing the configuration if necessary. Then we run the tests and finally, if necessary, close off the configuration to prevent it being used.

To run this, change the path values to a directory on your server if required. Remember that you are writing these files to your server, not the workstation.

I describe the methodology for the test harness, and how to set it up as a SQL Prompt snippet, in an article ‘How to record T-SQL execution times using a SQL Prompt snippet’.

These routines need to access temporary stored procedures. These are all stored on GitHub, and I’ll keep those updated. They are here, at JSONSQLServerRoutines along with several others that I use for processing JSON. For this example, create the #SaveJsonDataFromTable and #ArrayInArrayJsonDataFromTable temporary stored procedures in the same query window before running the following code.

/* lets just check the config and make sure that xp_cmdshell is enabled. */
DECLARE @Settings TABLE (
    name sysname, minimum INT, Maximum INT, config_value INT, run_value INT);
INSERT INTO @Settings (name, minimum, Maximum, config_value, run_value)
  EXECUTE sp_configure @configname = 'show advanced options';
IF NOT EXISTS (
  SELECT * FROM @Settings WHERE name = 'show advanced options'
  AND run_value = 1)
  BEGIN
    EXECUTE sp_configure 'show advanced options', 1;
    RECONFIGURE;
  END;
INSERT INTO @Settings (name, minimum, Maximum, config_value, run_value)
  EXECUTE sp_configure @configname = 'xp_cmdshell';
IF NOT EXISTS (
  SELECT * FROM @Settings WHERE name = 'xp_cmdshell'
  AND run_value = 1)
  BEGIN
    EXECUTE sp_configure 'xp_cmdshell', 1;
    RECONFIGURE;
  END;
go
/* start of timed run */
DECLARE @log TABLE 
  (TheOrder INT IDENTITY(1,1), 
  WhatHappened varchar(200),
  WHENItDid  Datetime2 DEFAULT GETDATE())
USE adventureworks2016
----start of timing
INSERT INTO @log(WhatHappened) SELECT 'Starting Writing out every table'
--place at the start
DECLARE @ourPath9 sysname = 'C:\Data\RawData\AdventureWorks\XML\';
Declare @command9 NVARCHAR(4000)= 
'EXEC xp_cmdshell ''bcp "SELECT * FROM ? FOR XML AUTO"  queryout "'
     +@ourPath9+'?.xml" -S '+@@Servername+' -T -c -C 65001 -t'', NO_OUTPUT;'
EXECUTE sp_msforeachtable @command9
INSERT INTO @log(WhatHappened) 
    SELECT 'Writing out every table as XML  took '
    --log the time taken to get to this point
/* first lets try using JSON array--in-array format */
DECLARE @ourPath1 sysname = 'C:\Data\RawData\AdventureWorks\JSONArrayInArray\';
Declare @command1 NVARCHAR(4000)= '
DECLARE @Json NVARCHAR(MAX)
EXECUTE #ArrayInArrayJsonDataFromTable @TableSpec=''?'',@JSONData=@json OUTPUT
CREATE TABLE ##myTemp (Bulkcol nvarchar(MAX))
INSERT INTO ##myTemp (Bulkcol) SELECT @JSON
EXECUTE xp_cmdshell ''bcp ##myTemp out "'+@ourPath1
     +'?.JSON" -c -C 65001 -S '+@@Servername+' -T '', NO_OUTPUT;
DROP TABLE ##myTemp'
EXECUTE sp_msforeachtable @command1
INSERT INTO @log(WhatHappened) 
SELECT 'Writing out every table as Array-in-Array JSON took '
--log the time taken to get to this point
DECLARE @ourPath2 sysname = 'C:\Data\RawData\AdventureWorks\JSONObjectInArray\';
DECLARE @command2 NVARCHAR(4000)= '
DECLARE @Json NVARCHAR(MAX)
EXECUTE #SaveJsonDataFromTable @TableSpec=''?'',@JSONData=@json OUTPUT
CREATE TABLE ##myTemp (Bulkcol nvarchar(MAX))
INSERT INTO ##myTemp (Bulkcol) SELECT @JSON
EXECUTE xp_cmdshell ''bcp ##myTemp out '+@ourPath2
    +'?.JSON -c -C 65001 -S '+@@Servername+' -T '', NO_OUTPUT;
DROP TABLE ##myTemp'
EXECUTE sp_msforeachtable @command2
INSERT INTO @log(WhatHappened) 
SELECT 'Writing out every table as Object-in-Array JSON took '
--log the time taken to get to this point
DECLARE @ourPath3 sysname = 'C:\Data\RawData\AdventureWorks\TabDelimited\';
DECLARE @Database3 sysname = Db_Name(); --over-ride this if you need to.
DECLARE @command3 NVARCHAR(4000)= '
EXECUTE xp_cmdshell ''bcp  ?  out '+@ourPath3+'?.Tab -c -C 65001 -d'
    +@Database3+' -S '+@@Servername+' -T '', NO_OUTPUT;'
EXECUTE sp_msforeachtable @command3
INSERT INTO @log(WhatHappened) 
SELECT 'Writing out every table as tab-delimited BCP took '
--log the time taken to get to this point
DECLARE @ourPath4 sysname = 'C:\Data\RawData\AdventureWorks\NativeBCP\';
DECLARE @Database4 sysname = Db_Name(); --over-ride this if you need to.
DECLARE @command4 NVARCHAR(4000)= '
EXECUTE xp_cmdshell ''bcp  ?  out '+@ourPath4+'?.data -N -d'
    +@Database4+' -S '+@@Servername+' -T '', NO_OUTPUT;'
EXECUTE sp_msforeachtable @command4
INSERT INTO @log(WhatHappened) 
SELECT 'Writing out every table as native BCP took '
--log the time taken to get to this point
DECLARE @ourPath6 sysname = 'C:\Data\RawData\AdventureWorks\CSV\';
DECLARE @Database6 sysname = Db_Name(); --over-ride this if you need to.
DECLARE @command6 NVARCHAR(4000)= '
EXECUTE xp_cmdshell ''sqlcmd  -d '
    +@Database6+' -u -E -h -1 -s, -W -Q "set nocount on; SELECT * FROM ?" -S '
    +@@Servername+' -o '+@ourPath6++'?.CSV'', NO_OUTPUT;'
EXECUTE sp_msforeachtable @command6
INSERT INTO @log(WhatHappened) 
SELECT 'Writing out every table as SQLCMD comedy-limited took '
--log the time taken to get to this point
SELECT ending.whathappened, 
    DateDiff(ms, starting.whenItDid,ending.WhenItDid) AS ms 
FROM @log starting
INNER JOIN @log ending ON ending.theorder=starting.TheOrder+1
UNION all
SELECT 'Total', DateDiff(ms,Min(WhenItDid),Max(WhenItDid))  
FROM @log 
ORDER BY ms asc
--list out all the timings
go
DECLARE @Settings TABLE 
    (name sysname, minimum INT, Maximum INT, config_value INT, run_value INT);
INSERT INTO @Settings (name, minimum, Maximum, config_value, run_value)
  EXECUTE sp_configure @configname = 'show advanced options';
IF NOT EXISTS (
  SELECT * FROM @Settings WHERE name = 'show advanced options'
  AND run_value = 1)
  BEGIN
    EXECUTE sp_configure 'show advanced options', 1;
    RECONFIGURE;
  END;
INSERT INTO @Settings (name, minimum, Maximum, config_value, run_value)
  EXECUTE sp_configure @configname = 'xp_cmdshell';
IF NOT EXISTS (
  SELECT * FROM @Settings WHERE name = 'xp_cmdshell'
  AND run_value = 0)
  BEGIN
    EXECUTE sp_configure 'xp_cmdshell', 0;
    RECONFIGURE;
  END;

Conclusions

It is very useful to run tests like these, and I caught several bugs while doing so. However, I much prefer testing things rather than waving my hands and arguing.

What I’d conclude from all this is that JSON is a good way of storing data and isn’t really any bulkier as a format than any other way of doing it. When data is zipped, it seems to boil down to the same size whatever the format you use. Obviously, Native BCP is the quickest and neatest way of ‘dumping’ data but it isn’t easy to read, and you cannot prepare data from another source and import it as native BCP because it isn’t a data transport medium. If you want an unzipped tabular format with the robustness of JSON and the size of CSV, then JSON Array-in-array is the one to go for.

None of the delimited formats are safe in that it is always possible that column value could contain an unescaped character that is used as a delimiter. CSV, in contrast, would be fine if there were a reliable way of doing it in BCP. If you want a safe way of transporting data, then XML or JSON is an obvious choice but who would use XML when there was an alternative?

The post Saving Data to Various Formats, Using SQL appeared first on Simple Talk.



from Simple Talk http://bit.ly/2EPSsgn
via

Friday, December 21, 2018

The Single Version of the Truth

If only there were a ‘single version of the truth’ in data and data analytics.

Unfortunately, data and everything that derives from it is subjective: it cannot be disentangled from our cultural biases. We can only find the version of the truth that fits the evidence and our cognitive map of the world we live in, clarify it as best we can, and run with it.

Although most data professionals would agree that the single version of the truth is a chimera, they would disagree with the aim of finding a version of the truth you like and running with it. Why? It reeks of the idea of manipulation of the data and is therefore seen as being pure evil.

This reaction is logical and predictable. It is the discipline of pure science. It will not be shared by people who are on, or above, a CxO level of management, or people who have consciously chosen jobs at big PR agencies.

These people will know very well from first-hand the sad truth that:

  • There is no way you are going to beat your competitors by having only a fair competitive advantage.
  • Statistics are used nowadays to create realities (if you torture data long enough, it will confess).
  • The human-behaviour-as-a-service is a driving factor in any economy nowadays, and the stakes are very high to maintain a certain level of well-being (at almost any cost)

These people are the servants of these rules, not the masters. They are obliged to create truths that fit the realities constructed by the people that they need to persuade. Ideas must be channeled in the context of those realities in a palatable way. We all come with mental schemas that we use to make sense of the booming, buzzing confusion around us. Humanity has to adopt these world-views off-the-shelf, uncritically; they vary enormously with their fit with reality. There is just too much information out there to gather and filter the information carefully, but instead, it is much easier to just ingest a well-served and garnished theory of what life is about.

Even if we are made aware of the puppeteer’s ropes, we generally believe that decision-making needs to be fact-based to be functional and correct.

We would still believe this, even if every person working with data analysis in some way would admit that they are fully capable of bending any data into any shape they want. We’d stick to the idea even if these august data scientists were all able to first prove that what they did was correct, and then prove that it wasn’t correct.

Past generations imposed high levels of integrity on their professions to try to prevent the manipulation of data getting out of hand. To an extent, it worked: even famous statisticians such as Sir Cyril Burt were ‘outed’ and disgraced when they were caught faking or manipulating data. We’ve lost much of the self-regulation of the profession, and this has allowed the puppet ropes to be stronger than the constraints on responsible scientific method. Trends and anomalies are claimed to be significant when they aren’t, and inconvenient data is removed as an ‘outlier.’ Inappropriate statistical methods are used, often in a ‘fishing trip’ until significance is ‘hooked.’

Even if data scientists had scientific integrity, their customers or employers are less likely to suffer the same restraint. Give a million bucks to a PR agency, and they will run a garlic campaign to the skies. And the public will love that garlic chewing gum and will ask for more. Individuals would hate it, but the masses will love it.

If we could bring self-policing back to the profession of data science, could we then establish an ethical dimension to the management of the vast international corporations and political forces that have increasingly dominated the past century and a half? It would be difficult. Historically, even when the promise of hell-fire was a believable threat against liars, swindlers, and usurers, the merchants managed to stave off the perceived threat by the paid remission of sins. It seems that money and honours can salve a conscience and neutralize any counter-force.

Perhaps we have unwittingly hit on the solution: When, how and what would make ethics in data profitable? Can even commerce itself be made more effective by a strongly-enforced ethical standard? After all, the Quakers managed it. The answer is that ethical commerce, when a word is a bond, takes far less time and energy because it doesn’t require the paperwork, the checks, the insurance and the legal work. If in data science, we can trust the input data, it is all so much easier. There is so much less we need to do. Likewise, without deliberate ‘fake news,’ and fake claims that go unchallenged, we don’t have to read so much and cross-check. Deceit takes a lot of energy.

The post The Single Version of the Truth appeared first on Simple Talk.



from Simple Talk https://ift.tt/2BzdFHj
via

Wednesday, December 19, 2018

Introduction to AWS Elastic Beanstalk

This article covers the .NET Core Web API on an AWS Elastic Beanstalk. I’ll give an overview of what an Elastic Beanstalk is, create a .NET Core API on an Elastic Beanstalk, configure the Elastic Beanstalk to a specific environment, and provide code to allow you to check the health of your application.

First, you must get your development environment established. I will describe what an AWS Elastic Beanstalk is. Then, I’ll walk you through creating an API and installing it with some knowledge passed along.

You can find out how to install the VS components, navigate AWS and set up account privileges in my previous article. Make sure you have everything in place if you wish to follow along with this one.

During this article, you will be visiting the consoles for Elastic Beanstalk and S3. The top banner of the console website has a dropdown called Services. Chose that dropdown for ease of navigating between console screens.

AWS Elastic Beanstalk

You are probably wondering just what an AWS Elastic Beanstalk is. I know the first time I heard it, I did. To understand you must learn about EC2.

AWS EC2 is the acronym for Amazon Compute Cloud. Think of it as a virtual machine. AWS has several prebaked virtual machine instances that you can use. These prebaked instances are called AMI (Amazon Machine Images), and there are various images. For example, there are Linux images (e.g. Red Hat, SUSE, and Ubuntu) and Window images (e.g. 2016 server, 2012 R2, 2008 R2 and SP2). You get to determine the instance type you want to use. Each instance type has an appropriate price tag. There are free types, of which I use to learn more about AWS. Within this laundry list, you determine the number of CPUs, memory, storage, performance, and other related items that you need. Treat EC2 instances as you would a physical machine.

Elastic Beanstalks are a wrapper for managing your EC2 instances. You still decide the platform you want the Beanstalk to contain. You decide to have a load balancer or not. No load balancer means only one EC2 instance to work with. Load balanced you need to determine the minimal number of EC2 instances and the maximum number of EC2 instances you want running. This translates into dollars you are willing to spend on VMs. You configure when to add additional EC2 instances. Load balance will instantiate on demand additional EC2 instances. Think of it this way, it basically growing and shrinking EC2 instances on demand; taking the guess work out of what you think you your computing needs are for your application, just like an accordion. For this article, I am going to step you through creating a Beanstalk with Windows in the free tier configuration.

Creating an Elastic Beanstalk

Navigate to the AWS Elastic Beanstalk service within the AWS console. Select the Get started button.

Define the application name, choose the platform you want to work with (Windows for this use case), and select the Sample application for the application code. This article uses the sample application to walk through the configuration parts of a beanstalk. Once everything is in place, click Configure more options.

On the next screen, you’ll see a series of cards that allow you to configure each area of the Elastic Beanstalk. In this article, I’ll discuss the Instances, Capacity, Load balancer, Monitoring, and Tags cards in more detail.

The Instances card tells you what size of EC2 instance you have. Leave it at the t1.micro level. This level is free to use.

The Capacity card is where you specify the number of instances for load balancing. The default is single instance; there is a second option of Load balanced. Click Modify on the Capacity card and make the following changes:

  • Set the Environment type to Load balanced.
  • Set the Instances have a Min value of 1 and a Max value of 2.

  • Any Availability zone is fine.
  • The Scaling triggers setting determines when the next instance should be created. Change it to CPUUtilization since these EC2 instances are tiny.
  • Leave Average as the Statistic even though there are other options.
  • Change Unit to Percent.

  • Leave Period and Breach duration to be five minutes respectively.
  • Change the Upper threshold to 60 Percent and the Lower threshold to 20 Percent.
  • Leave the Scale-up increment and Scale-down increment to 1 and -1 respectively.

Don’t forget to save your work. When you return to the main configuration page you will see the Load balancer card now has more information.

When you navigate to the Load balancer card by clicking Modify, you will see the following

Leave the current values in place. It is here where you can change your address to use HTTPS. Click Cancel to go back to the main configuration screen.

For now, do not do anything with the Monitoring card. This will be covered later in the article.

The last card I want to point out is the Tags card. As you can see, it is for key-value pairs. These key-value pairs can be used for searching in the EC2 instance page when you are looking for specifics. I have added the key Environment and the value Development. Also, these tags do appear in the billing also to give you a gut check of what it is you are paying for.

Now that it’s configured, create the app by clicking on the Create app button. The next screen is a console-like screen showing you what is happening.

When it is completed, you’ll see the dashboard. It can take quite a while to start up, so be patient!

The Health will be either Green, Yellow, Grey, or Red. Green means all is well; Yellow means something is not quite right; Grey is when there is a transition going on (e.g. installing app, refreshing, or rebuilding everything); and Red means there is a serious problem, and nothing is working.

Remember at the beginning of the article, and I talked about EC2 instances? You can now see the EC2s that the Beanstalk created. Navigate to EC2 via the AWS console. On the landing page choose Running Instances under the Resources title or Instances in the left navigation bar; they both go to the same page.

Select the instance you want to interrogate, and you’ll see the information in the lower half of the page. You will only see one EC2 instance because of how you configured the Capacity card. You set the Min value, Max value, and Scaling Trigger values; since there is nothing taxing the EC2 instance, you will only see one instance. Once you go over the Scaling Trigger values, another EC2 instance will automatically be created. There is a lot of information for you to digest on this EC2 page. Navigate to the different tabs to review the information if you wish, but I don’t want to dive into EC2 instances details in this article; I want to make you aware of what is happening with Elastic Beanstalks.

Now that you have seen how to create an Elastic Beanstalk with a sample application, clean up your environment by deleting the beanstalk. Navigate back to Elastic Beanstalk and choose the Actions button/dropdown and select the Delete application.

It will ask you to confirm your delete action. Choose Delete. You will see that the application turns grey. If you go back to the EC2 dashboard, you will see that the EC2 instance has been removed. Now that you have a high-level understanding of AWS Elastic Beanstalks, it’s time to write some C# code.

Creating the VS Project

Create a Visual Studio solution/project by choosing ASP.NET Core Web Application within the New Project UI.

On the next screen, New ASPNET Core Web Application, choose API. I unchecked the checkbox to Configure for HTTPS since that is not within scope of the article.

In the Solution Explorer, you will see your C# API solution and project.

Publishing the Application

The first thing I want to show you is you can publish to AWS Elastic Beanstalk from Visual Studio. Right-click on the application and select Publish to AWS Elastic Beanstalk…

The Publish to Amazon Web Services dialog window appears. Choose Next.

The application name is filled in for you automatically. You may change it if you like. Think of this as the container that will house your applications in the various environments (e.g. Development, Integration, Testing, Stress, Beta, Production, and the list can go on). You don’t need all the environments in this container; this is a conversation amongst the teams. Regardless, you will need to provide an environment name. For the environment name you can either choose from the drop down (name of the application plus dash -dev, -test, or -prod) list or type in a name of your choice.

Next you will want to check the availability of that URI, so click the Check availability… button.

If the name is not available, use something else. Chose Next which will present the AWS Options page.

As you can see, you will define what the environment setting are. I choose the default container type, which is Windows. You can change this if needed. I choose the default instance type, t2.micro, instead of changing the type.

Key pair is something you will want to think about. I won’t discuss it in this article other than to say if you want to communicate between AWS parts, you will want a key pair. I kept the Single instance environment option checked. Chose Next to get to the permission page.

You can leave the defaults or changes them as needed. You can also create your own roles, but that is outside the scope of this article. Chose Next to go to the Application Options page.

For now, keep all the defaults. Later on, you will change the Health check URL. Chose Next to get to the Review page.

As you can tell, this page allows you to review what you have configured. You can go back if you wish to make the necessary adjustments. I kept the checks in the two checkboxes checked. The Open environment status windows when wizard closes option allows you to see what is occurring on deployment from Visual Studio. You could go to the AWS console to watch it also. The Save settings to aws-beanstalk-tools-defaults.json and configure project for command line deployment will generate the JSON file aws-beanstalk-tools-defaults.json, more on this later. Select Deploy. The environment status window appears. After a few minutes, you will see success in the Visual Studio page.

You will also see that the application has been deployed within Visual Studio. Bring up the AWS Explorer. Within the tree, expand AWS Elastic Beanstalk, then expand the application.

AWS also shows a popup telling that the deployment is done at the bottom of the screen.

Note that a new file appeared in your solution, aws-beanstalk-tools-defaults.json. This file contains the information for deployment.

You can also watch progress in the AWS console by navigating to Elastic Beanstalk. When the application setup is complete, you will see the following within the AWS console:

Click on the application name and then Configuration to navigate to the configuration page. Note how the configuration looks different than when you manually set it up through AWS.

Also navigate to the EC2 instances to see an EC2 instance with your application environment name. Later on, you will reconfigure everything, but first make sure that the deployed code runs.

Testing the Application

You can find the URL to your application from the AWS console at the top of the screen or from the link displayed on the Visual Studio deployment page. For my example, it is https://ift.tt/2GsXSiV. When you created the API application, a ValueController class is generated for you within the Controllers folder. At the top of this class you will see the Route attribute that defines the route to this controller. This Route takes in a string parameter. It is set to api/[controller] so that you do not have to specify the controller specifically for each controller. The framework replaces [controller] with the class name minus Controller. For this example, it will become api/values. Take the URL and append the path to the values controller that the template created for you to get https://ift.tt/2R2FVf2. Navigate there with your favorite browser to see the http get output:

Go back to the Visual Studio project and take a look at the aws-beanstalk-tools-defaults.json file. This file tells us what AWS needs to know for deploying the application.

The next step is to add code that will function as a health check to assist you or your DevOps person to interrogate the application. Create a new class under Controllers called HeathcheckController. There will be two methods within this controller, both are HTTP Get verbs. The Get without an input parameter is the one used in configuring the AWS Healthcheck. That will be line 13 in the aws-beanstalk-tools-defaults.json file. The only thing it will return is Ok() which yields an Http status code of 200. The second Get with a string input parameter is the one you will be working on the most. For now, you will only define the value env which will return the environment name that the Windows VM thinks it is.

What business value does this add? Good question. If the application is down, you have a quick method to ask your application certain questions, such as

  • Can you talk with the database?
  • Can you talk with other services?
  • Are you configured correctly?
  • And so forth

Also, the health check can be used as part of installation smoke testing. This is a quick way to make sure something is not messed up in the configuration. Here is the code for the new HealthcheckController class.

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace GeraldsWebApplication.Controllers
{
    [Produces("application/json")]
    [Route("api/Healthcheck")]
    public class HealthcheckController : Controller
    {
        [HttpGet(Name = "GetAppStatusCode")]
        public IActionResult Get()
        {
            return Ok();
        }
        [HttpGet("{key}", Name = "GetSpecificAppStatusCode")]
        public IActionResult Get(string key)
        {
            dynamic result = new ExpandoObject();
            switch (key.ToLower())
            {
                case "env":
                    result.Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "unknown";
                    break;
                default:
                    result.Add(new KeyValuePair<string, object>(key, "undefined"));
                    break;
            }
            return Ok(JsonConvert.SerializeObject(result));
        }
    }
}

Hit F5 to run the app. The launch settings are defined in the launchSettings.json file found in the Properties section of the project. My project is using port 51974, and yours will likely be something different. As you see in the profiles for IIS Express, the default launch URL which is set to api/values which corresponds to the ValuesController Get method.

When running the app as you did earlier, you get:

Navigate to http:// localhost:51974/api/healthcheck/env (replacing your port) and you’ll see:

Now deploy this project to see how the new controller behaves. Just like before, right click on the project and select Publish to AWS Elastic Beanstalk… Notice that your previous deployment appears in the deployment target section. Chose the Redeploy to an existing environment radio button and select your project name.

Chose Next. Note that you skip the several configuration wizard screens and land on the options section. Chose Next to go to the Review page and then select Deploy.

Now you can smoke check your deployed application. Go to https://ift.tt/2R2FVf2. Yes, you can still see the values:

Now navigate to http://geraldswebapplication-dev.us-west-2.elasticbeanstalk.com/api/healthcheck/env to see the results:

Unknown, hmm. The application’s VM hasn’t been configured. The Tags section within the application won’t assist because they do not reside within the Windows world, so to speak. You need to add a command within the code to tell AWS deployment to add the environment variable.

Within the AWS documentation for Configuration Options, you can set commands for before creating the environment, during the environment creation, and after the environment has been created. For this case, you will be running the command after the environment is set up.

To create the command, create a new folder in the API project called .ebextensions. Within that folder create a file called command.config. Add the following text to that file:

commands:
  01_create_env_variable:
    command: "powershell.exe [Environment]::SetEnvironmentVariable('ASPNETCORE_ENVIRONMENT', 'Development', 'Machine')"

Please note the indentation on the second and third lines. If you do not have that indentation, you will get a warning message telling you that the values will be skipped when you are deploying the application. The command will not run. In this use case the ASPNETCORE_ENVIRONMENT variable will not be set.

I use PowerShell to do my scripting work. As you see in the command line a PowerShell executable will set an environment variable, specifically ASPNETCORE_ENVIRONMENT with the value of Development. The ASPNETCORE_ENVIRONMENT variable works with the .NET Core API appsettings.json to set configuration values.

Open the properties of the command.config file and change the Copy to Output Directory option to Copy always.

Redeploy to AWS. You’ve done the drill a couple of times now.

It’s time to do the smoke check again. You’ll see the value when calling the values controller. The api/healthcheck/env now displays which environment you are working with.

I have only discussed adding code to see what environment I am working with. I have extended the health check controller to check the assemblies’ version, call a database to ensuring the application can talk with it, and other services too. The health check controller is an entry point into your application that will assist you in troubling shooting and smoke testing your application.

The command.config file is needed for deployment because, when a new EC2 instance is created, it uses that file to configure the server. You only deployed one instance from Visual Studio. Now change that and test that the environment configuration follows the code.

Changing the Configuration

Now that your application is working as expected, you can change the configuration. Navigate to the AWS Console and to the application environment to change the capacity configuration values from one instance to two. Notice that the load balancer is not configured.

Click the modify link of the Capacity card to view the options. Change the options to match the configuration that you set up in the first example.

  • Change the environment type from Single instance to Load balanced.
  • Change the instance Min value from one to two, leaving the Max value at four.
  • Change the Scalling triggers so that the Metric is set to CPUUtilization
  • Set Unit to Percent.
  • Change Upper threshold 60 and lower threshold to 20

Click the Apply button. You will get a warning that the world is changing. Click Confirm.

Your application is now going offline to reconfigure itself.

Once the app status is green again, go back to the configuration section to examine the capacity and the load balancer cards.

As you see from the cards, you will always have two instances running with a maximum number of four instances and a load balancer. Go to EC2 to see your two instances.

Now configure the health check monitoring. You are going to set the Health check path value to be /api/healthcheck. To do this click Modify on the Monitoring card and change the health check path.

Click apply. This time you will not get a warning message but the system will restart itself to apply the health check. I have noticed that setting this health check pinging is like the ping scripts we use to write to keep IIS awake.

You could have made the same changes when deploying the app from within the Visual Studio AWS Deployment Wizard. On the AWS Options page you could have unchecked the Single instance environment checkbox.

Within the options page, you could have set the health check url. Meaning you have the HealthCheckController ready to be called.

On the Review page, ensure you have checked the Generate AWSDeploy configuration checkbox to generate the aws-beanstalk-tools-defaults.json file. Note that you will see that the capacity is 1-4 instances, there is a load balancer, and the Health check path is filled in with what is defined in the deployment wizard within Visual Studio.

Summary

This article has given you an introduction to AWS Elastic Beanstalk. You learned that the beanstalk is a wrapper around AWS EC2 instance(s). You can configure the beanstalk to be load balanced so that the number of instances being used can grow when demand increase and shrink when demand decreases. You have successfully deployed a .NET Core API to a beanstalk. Along the way, you learned that you can configure the Windows machine with commands. I introduced a controller called HealthCheck to check the health of your application, you must determine what that means.

The post Introduction to AWS Elastic Beanstalk appeared first on Simple Talk.



from Simple Talk https://ift.tt/2GtA5zr
via