A simple Azure SQL DB to Azure SQL DB External Table How To

I’m working on an app for a client with some interesting requirements. The app has its on Azure SQL DB thats ultimately for staging data, but is part of a project with a Data Warehouse. We needed some office location data from the data warehouse to populate a drop down in the app and I decided to try the EXTERNAL DATA SOURCE feature.

External data sources seem similar in concept to linked tables but are much different in practice. They let you connect to hadoop data, azure blob storage, do elastic tables, and expose a table in one database to another. The last one is the least sexy, but the one I want. It’s also the option with the least attention in books online and blogs. I’m here to fix that.

Defining our problem

Of course these are not the real names of my clients servers, dbs and tables.

The data warehouse is on a server called mywarehouse.database.windows.net. The database name is myWarehouse. It has a table called dbo.dimFacilities. We want to expose a subset of that tables columns to a database called loadingDb on myapp.database.windows.net.

Doing the work

loadingDb is going to need to authenticate to myWarehouse and perform some selects. Therefore we need to create a user in myWarehouse. for loadingDb and assign it to the db_datareader role.

CREATE USER app_dw_reader WITH PASSWORD = '************';
GO
EXEC sp_addrolemember @rolename = 'db_datareader', @membername = 'app_dw_reader';
GO

It’s probably better to create a custom role with just the selects on the table we want, but that’s an exercise for the reader. You are not limited to contained users here. You can also use AzureAD users or users associated with a login.

Now its time to turn our attention to loadingDb. The first two objects we will create are a MASTER KEY and a SCOPED CREDENTIAL.

CREATE MASTER KEY ENCRYPTION BY PASSWORD = '**************';
GO
CREATE DATABASE SCOPED CREDENTIAL dw_reader WITH IDENTITY = 'app_dw_reader', SECRET = '********';
GO

Note the MASTER KEY password is a distinct password the SCOPED CREDENTIAL password must match the users password. The master key is used to encrypt the scoped credential. When you change the password for app_dw_reader, you need to use ALTER DATABASE SCOPED CREDENTIAL to update the secret.

Now that we have that the next object is the external data source This somewhat analogous to adding a linked server entry.

CREATE EXTERNAL DATA SOURCE data_warehouse
WITH (
TYPE = RDBMS,
LOCATION = 'mywarehouse.database.windows.net',
DATABASE_NAME = 'myWarehouse',
CREDENTIAL = dw_reader
);
GO

Note this command will succeed even if the credential is invalid as long as the credential object exists. You don’t get an error until you try to query the linked table. Luckily its a useful error.

Now we need to define the table and the columns. You can define just a subset of the columns, but column definitions must match exactly or you get an error on select. Luckily, the errors returned if the select failed list the column in question.

CREATE EXTERNAL TABLE [dbo].[dimFacility]
(
[facilityId] int NOT NULL,
[facilityName] NVARCHAR(100) NULL,
[country] NVARCHAR(64) NULL,
)
WITH (
DATA_SOURCE = dev_data_warehouse
);
GO

Tangential note on column definitions. If you are using sys.columns.max_length to get the length of NVARCHAR columns divide that by two because that is length in bytes. The azure portal query editor doesn’t show column lengths, so I decided to use DMVs.

Now if everything worked out well you should be able to do a SELECT * FROM dbo.dimFacility; in loadingDb and get you data. Congratulations!

Using Power Query For Excel as an Azure AD Dashboard

Azure Active Directory is a great piece of technology that can do several things around authentication. However, the UI provided by portal.azure.com is lacking, and documentation can be a little unwieldly. This article serves as the first in a series of that will show you how to use Microsoft Power Query (and maybe some VBA) to create a better dashboard for user and application management for Azure AD.

Technologies utilized

In this series we will be using the following technologies.

  • Microsoft Excel to host the dashboard. Power BI would also work, but I don’t know Power BI (at least yet).
  • Microsoft Power Query to query the graph APIs to get the data we need and present it into Excel Tables
  • Windows Azure Graph will be the OData REST API that Power Query will use to

I have the beginnings of a dashboard that solves some problems I’ve encountered during about a year of Azure Development. I still have to figure out a few things to get the dashboard I really want. While I’m pretty good with Excel, I am very new to Power Query. As an advanced Polygot programmer that is new to the Power Query language I struggle to create code elegant reusable code in Power Query due to my ignorance of its syntax. I’ll be learning along with you.  This list might grow.

Getting the Dashboard

I’m actually not sure yet. The main artifact of this project will be an Excel Spreadsheet with Power Queries for the Azure Graph APIs, and maybe some VBA to push the data. I’d like to store the Power Query code as text files in GitHub. Solutions for storing VBA as text in version control exist (e.g. RubberDuck VBA).

Also, I need to figure out a reliable way to strip all the data from my tenant from the spreadsheet.

I’m going to also look into distributing this via OneDrive or Office365 SharePoint. I’m actually not sure if I can make public links there.

Why not Microsoft Graph?

The short answer is at the time I started using Azure AD, many things I wanted to do didn’t work yet in the Microsoft Graph. One of the main use cases I will talk about here is B2C users, which as of 2018-08-31 is still not supported by the Microsoft Graph. Support does say “Coming soon.”

The long answer is as follows Certain operations require you to use one of two graph APIs, the old Azure Graph (https://graph.windows.net) or the new Microsoft Graph (https://graph.microsot.com). To clarify that statement, while both graph APIs expose more functionality than the azure portal (http://portal.azure.com), some operations only work with one endpoint. In theory eventually the Microsoft Graph will be a complete superset of the Azure Graph. That hasn’t happened yet.

Articles in this Series

On dishwashers and development.

Around 1976 a great thing happened in the house I would come to purchase in June of 2013. A KitchenAid KDI-18 was installed. Those with a penchant for vintage appliances believe this is one of the greatest home dishwashers ever made. Their spouses generally believe they are too loud.

Mine gave up the ghost recently. I could have saved it, but it was the dishwasher or the marriage. I went with a Bosch SHXN8U55UC. It’s whisper quiet. Like all German Dishwashers it has no heating element, but is engineered to produce smaller water droplets that evaporate quicker. Its gets the water hotter than the more expensive Mieles. It has a sanitize mode so I don’t have to take an extra step to sterilize my infant’s bottles and pacifiers. It uses very little water and is incredibly energy efficient. It’s like comparing a 1976 Cadillac DeVille to a modern BMW 7 series.

The cost of this efficiency is time. A cycle takes 2:09 and if you add sanitizing it climbs to 2:30. There is a save time function that takes an hour and change as well as a 30 minute express function. In addition to all this, there is the temptation to overload the dishwasher and pack things too close together. If you are not careful something might slip below the tray or be too high. Then a wash arm won’t rotate. All of these things means your dishes don’t get as clean.

This is very similar to software development. Putting too many things on the schedule or cutting back the delivery time frame might work in the short term. However, it means a more fragile result. Once I notice one dish is still dirty when unloading the dishwasher, It slows down my whole unloading process. I lost confidence in the operation of the machine. If I have to hand wash a dish it uses a lot more energy and a lot more of my time. Time I could better spend doing a DIY project around the house. I’m not a great handyman, but I’m the most talented handyman and tradesman on staff at my house. When I’m taken off my home improvement duties to deal with dishes that are not perfectly clean, it costs the house in materially significant ways.

So folks in conclusion, run your dishwasher on their full cycles unless its a very light load. Don’t let the dishes touch each other. Observe how well your dishwasher performs. Think about this next time you want an estimate cut and a schedule moved left.

In defense of the VBA developer

Yesterday I did what I was put on this earth to do, get into an argument on the internet. I  defended VBA.

https://twitter.com/flippbreezy/status/747856641903628288

. . .

 

Well with humility I present those thoughts here. However, before I present those thoughts I need to make three confessions:

  1. I use and have contributed to a tool that modernized the ALT+F11 VBA Editor.
  2. I have used and contributed to a tool that lets you make REST calls from VBA.
  3. I have written code to facilitate low level debugging of VBA with Sysinternals Process Monitor (procmon.exe).

Just to be clear, I am by no means a full time VBA programmer, I’ve simply dabbled extensively. In terms of hours logged or LoC its quite clear this is not a major endeavor of mine.

Ok my biases are reported. Full speed ahead with the apologia.

Sometimes Excel is the right tool for the job. There are many reasons for this.

Sometimes its a technical reason. For example, QuantLib is a really great quantitative library with binding for many languages such as C, C++ and Python. QuantLibXL is the excel binding for them. Excel is great at doing math and accounting. Quantlib just takes that to the next level with quantitative finance. It’s an obvious organic extension.

Sometimes you just need a little VBA. For example, in my sysadmin days I’d often be given spreadsheets of servers for audits. A little VBA would allow me to do reverse DNS lookups on the IP address columns in these spreadsheets. Whatever sin there is in adding VBA was a small one, and it would not be practical to not use Excel for the task because it wasn’t my decision.

Sometimes Excel is just being used to prototype a front end. Sometimes a developer that doesn’t want to write a web front end would rather use VBA-Web to write a quick API for an analyst for some REST services. This allows the analyst to own the front end and extend it, while the developer can do what they are good at. I’ve been in this situation. XL allowed me to be more of a back end programmer and not a designer.

Finally sometimes you’re in a silo in a large org with locked down desktops and cannot get Visual Studio, Python or R installed on your machine. However, you have office and VBA isn’t locked down. That decision to not support all those development environments is probably the right decision for the overall health of the org. A few smart people at the top lock everything down and they can scale out support issues with low salaried minimally trained help desk workers. Despite this your silo’s managers and developers allowing VBA abominations to grow beyond what makes sense within your silo. Its a crappy situation overall, but you have a silo doing the best they can to serve their larger organization even if the org cannot properly facilitate them. I’ve never personally been in this situation. However, I’ve interviewed at investment banks.. A former boss of mine worked at an investment bank that used VBA extenively. I’ve had many a beer with sysadmins at investment banks. Its quite clear to me why both sides do what they do.

Is excel often not the right tool for the job? Absolutely! It has been described as the second best tool for any task. The actual truth is it the tool people have and know how to use that gets shoehorned into a lot of tasks that could better be solved by other tools. Often these tasks have deadlines that makes excel the right tool at the moment pragmatically speaking. Excel is kind of like WD-40. WD-40 is a great solvent, that has some lubricating properties. However, its usually not the lubrication you want to use. Its great in a pinch if you don’t have machine oil. Just realize it’s going to quickly evaporate away unlike machine oil.

On Today is a Good Day to Die

Yesterday was SQL Saturday 517 in Philadelphia. As usual Joey D’Antoni(blog|twitter) and his team put on a great event. I look forward to coming back next year if I am selected to speak. On my way there, at the Molly Pitcher Rest stop where I put money on my E-ZPass, I sent a not particularly unusual tweet for me:

Now if you follow me on twitter you’ve probably seen me tweet that as well as extended forms that usually is a subset of the following.

Do something important today . Find your purpose in your utility to others. This way if today ends up being your last do on this earth, your last thought will be. “Today is a good day to die.”

However, someone that didn’t follow me, but was looking at the #sqlsat517 hashtag saw this and asked someone (who happened to be someone I know) if I was a terrorist. Unfortunately, I arrived late and this person left early. Therefore I could not personally assure this person I was not a terrorist. I’ve reached out through twitter, but this person does not tweet every day. Maybe that means he still actually got an email with my @reply. Regardless, I will do everything in my power to personally address his concerns if he still has them.

That being said, perhaps an extended commentary on the thoughts behind these tweets are in order.

First of all for the record, they are 100% inspired by Worf on Star Trek TNG and DS9. However, it’s evolved into so much more beyond that.

Second, lets talk about “Do something that matters.” Someone once complained that they felt it was depressing to read this because they felt their job was mainly “making rich white guys richer.” Well the point is to do something important, but for you to determine what is important. Maybe the main thing you can say about your job is it pays a lot better than anything else you’re qualified to do. Well maybe you get to mentor someone there, who will leave and help cure cancer. Maybe some customer  will indeed achieve greatness indirectly through your company. Maybe you can go home an volunteer in a soup kitchen. Maybe you can convince your boss to give back some contributions to an open source project you use at work. Maybe you will go home and change your kids diaper and play blocks with them. I’m not here to judge what you consider important. I’m not even sure what I consider important. I’m just saying, try to do something important every day. You can decide what is important, and if you need to alter the direction of your life to do more important things.

Third, lets talk about “find your purpose in your utility to others.” I think this is something we as a society are moving away from. People used to sign letters “I remain in your service.” Important people like George Washington who usually wrote to people of a lower station than him.  We’ve fallen away from formal letters, but we still send emails that are formal enough to warrant such a heady conclusion. Anyone that knows me knows I am a very independent person. However, I crave being useful. When a blog post by Thomas LaRock lead me to read The Broken American Male by Rabbi Shmuley Boteach, I rejected his premise that being a “human doing” is inherently a bad thing. Being a human doing that is overly concerned about money is certainly a bad thing. However, a well balanced human doing that does stuff for their family, their job, and for extra curricular organizations is a desirable thing IMnsHO.

Fourth, lets take a stab “Today is a good day to die.” I’ve never wanted to die. I’ve seen shrinks on occasion for moderate depression, but I’ve never been suicidal. The highest form of life I killed was a pig, which I ate part of. I’ve also slaughtered two chickens and a goat, and recommend all meat eaters do slaughter a mammal at least once in their life. There might be one or two people on this earth I wouldn’t mind seeing in the obituary section of the newspaper (no, not you), but I’d make all normal attempts to save their life if I saw them bleeding or unconscious. So in addition to not wanting to die, I’d rather avoid killing someone except to save the lives of others.

All that being said, we’re all going to die someday, and other than my religious beliefs about the afterlife, the best I can say about the matter is death is the one thing people actually think its a good thing to procrastinate over. As someone who files extensions on April 15th so I can file my taxes October 15th, I consider myself an authority on people opinions of procrastination. Despite our best efforts at procrastination, we will all die eventually. I have a young family now. It would suck for my wife and kids if I died. However, I’ve taken out life insurance to mitigate some of the more tangible losses. When life ends for me it will go on for everyone else. That day might be today, tomorrow or decades from now. Whenever it is, I do know that I’ve lived a fuller life and seen more things than most people that have ever lived on this planet, so it would feel selfish to say I’ve had anything but a good life. Therefore, is it that much a stretch to say today is a good day to die?

Is bro culture just more comfortable for males?

Zeorthly, and aside. This post as not inspired at all by this posts or the jerkwad that left Jen such crass feedback. Timing is coincidental.

I decided to meditate. Based on previous advice from @sqlanodyne I went with this guide, with the additional caveat that I’d do a lotus pose during the meditation no matter the cost or consequence. Over-committing made me the programmer I am today, perhaps in time it can make me someone that can meditate with my legs crossed. On the second day I had some lingering pain around my knees and I decided to take some yoga classes. I paid $50 for a month of unlimited classes at a hot yoga studio that had the virtue of being the closest yoga place to my house. I went to a class. I sweated. No full or half lotus was done. This is not about that. This is about me being in a yoga class with only one other male.

It went generally well. I felt generally comfortable. No one seemed uncomfortable by my presence. The instructor was not the best yoga instructor for n00bs, but I sat in the back, watched everyone, and made do with the situation. Years of being a socially inept shy person makes me comfortable in a socially uncomfortable situation. I have an odd feeling of familiarity when quietly observing others in an unfamiliar situation and following along.

Then I though about what would be a more comfortable situation for me. Something not comfortably uncomfortable, but comfortably comfortable. The answer is a weight room. A bunch of guys bigger than me, teasing me, but spotting me and pushing me to be stronger. Not at all an inclusive situation. A literal testosterone filled situation. However, I have experiences dating back to high school in a weight room. I have a place and a rank. That rank may be Omega, but in the Yoga studio I am Omega with an asterisk. I am other. In the weight room I belong. Someone will spot me. Someone will invite me into their groups rotation.

So what’s the conclusion? Mindfulness and relativity. The platinum rule. Treat others like they want to be treated, not how you want to be treated, because other people don’t want what you want. Maybe your comfortable with your brogrammer behavior. Maybe someone less white, less male and less twenty-something is not. Build an org where some feel like the omegas, but none feel like they have asterisks.

The dark side of learning from our mistakes

IT is largely unlicensed and unregulated. People have different feelings about this. As a college drop out with no certs besides a ZCE in PHP 5, I’m a big fan of the situation. One positive of this, is that most of the good people in IT tend to be self motivated to learn. We tend to learn from our mistakes, and learn from bad situations. However, the downside of this is mastery is often achieved through bad situations.

I’ve often said I’m paid as well as I am and I’m as skilled as I am because I was often underpaid and overworked in my youth. If I didn’t take jobs that didn’t pay enough that required more than I was capable of, I would not be forced to become the developer I am today. This is objectively true for me, and possibly for many others.

So what’s the dark side of this? Cheap bosses and clients got what they paid for. I got decent pay during my faux-apprenticeships. Decent companies and jobs existed for when I was ready for them. That is all kosher in my book.

The dark side is we suck at true mentorship and apprenticeship. Stackoverflow and other sites let us curate the tribal knowledge of how do do specific things. Training exists and great trainers abound. I’d like to think I’m a decent trainer. However, its hard to get an opportunity for one on one mentorship. I wouldn’t know how to teach a green developer in a holistic manner. I could just give them tasks and let them drown because it worked for me. However, I think there is a better way. I just don’t know what that way is.

Paying for our tools

Recently Karen Lopez pointed out something rather obvious in the Microsoft SQL Server Community. We’re cheapskates.

I don’t want to talk about training though. I want to talk about software. We don’t like paying for it ourselves. I think that’s kind of weird and bad.

In 2013, I purchased but didn’t renew an MSDN license. That’s about a grand. Over the years, I’ve given a lot of money to JetBrains for their .NET tools. Thanks to their new subscription model I only have to pay them $199 a year for all their tools. This is actually great news since I work in multiple languages these days. I also bought Zend Studio, a PHP IDE because I had to conduct corporate training with it.

Now, I am a contractor, so I don’t have a full time employer to buy me things. However, other than my current JetBrains subscription and Zend Studio, that’s all software I bought myself while a W-2 Employee working for someone else. The MSDN license was to work on open source software at home on my personal machine. While community edition makes this unnecessary now, I literally paid money for tools I used for work I did for free. While that seems crazy because it’s software, no one things its crazy that I bought a set of torx wrenches to replace the engine in my drill, which I use for personal projects around the house.

In addition, I’ve made various donations to OSS software over the years. Some projects I’ve donated money to include:

Now I understand everyone has different expenses and different life situations. However, one should consider these are the tools of our trade. The double edged sword about software development is that it is an unregulated and unlicensed field. This great for self-starters and those lacking formal education like myself. On the other hand, you usually have to do your own training on your own time because your employer often won’t. You don’t want to use your work laptop for that.

In addition many Open Source tools are often worked on by people for free. Donations rarely bring an income anywhere near what we can make through employment or contracting but, donations do help. They keep us happy, and sometimes let us pay for hard costs like the license to a profiling tool or hosting. Also, donations inspire us to fix your bugs.

What are your feelings on paying for licenses out of personal funds and donating to OSS? Share in the comments.

Moving beyond mansplaining

My name is Justin Dearing and I am a head down tactical white male geek. Between being good at what I do, and being white and male I get away with a lot of social ineptitude. Generally, I have no problem with getting away with being socially awkward for being good at my job as long as no ones feeling get hurt or no one has to clean up my messes. In other words, if someone says “Justin is awkward in conversations, he needs to iron his short and his desk is full of papers he never throws out, but damn he is a good coder,” that is a generally virtuous situation.  However if someone says “Justin’s desk is full of spilled food that bacteria is growing in and his argumentative method of conversation excludes a lot of people, but he’s a damn good coder” that is a viceful situation.

So with that guideline in mind, competence should excuse one from pointless social moors but not the purposeful ones, lets look at this article that came up in my tweet stream.

The article talked about mansplaining, but broke it down in a way that made it really hit home for me. Men like to hear the sound of their own voice. Mansplaining is a symptom of that. So this of course begs the question, “is there something more basic than mansplaining that is a viceful behavior, or is seeking to talk for the sake of talking inherently viceful?”

I don’t have an answer, but I know I definitely enjoy having an audience, and I am long winded. I speak at several SQL Saturday’s across the country. I pay my own way for these. For the majority of my time doing them I was a W-2 employee of companies that were not sponsoring the events I spoke at. Even now as a 1099 contractor, most of my work is dealing with DB2 on the IBMi (formerly iSeries and AS/400 before that). I don’t have a commercial interest in being there. Why do I speak at SQL Saturday?

  • I love getting to present on the topics I choose
  • Networking is good, and yes some of my income I can directly attribute to “someone saw me speak at PASS and recommended me for something” However, I’m running a huge net loss in terms of money I spent to get to SQL Saturday versus direct opportunities it gave me.
  • I do get to do precons, but I’ve yet to run a profit on one of them
  • Usually there is a speaker dinner, but considering I usually need a hotel room and might need a plane ticket, its the most expensive free dinner money can buy.
  • I love getting in front of people and having them listen to me.

So is my speaking at SQL Saturday a direct result of the same root cause of mansplaining? Most likely. Is me speaking at SQL Saturday a bad thing? I don’t know. If so what’s the correct solution? Paying speakers? I know a lot of well paid people that like the sound of their own voice. What are your thoughts?