In Search of a New Normal

The last couple of weeks have been a ride. A day or two after starting insulin my vision went all blurry. Last week was a write off. I went through my day job by increasing all the fonts and straining for hours – accomplishing almost nothing.

At the end of the week I had another appt at the clinic and the nurse suggested I go get magnifying glasses at the dollar store. I did and it’s not perfect but I’ve been much better off since then. It is due to the dramatic change in blood glucose levels. The nurse said it should come back within 8 weeks and indeed it is improving this week.

My sleep pattern is in flux as well. I used to get up 4 or 5 times in the night to pee (a big symptom of diabetes FYI). Now I’m not getting up at all but my patterns have been inconsistent. Some days I wake up at 5.00 and lay there till 6.30 not feeling particularly refreshed. Another day I will sleep till 8.30. I guess my body is finding a new normal.

Somehow this journaling has become more about learning to live with diabetes and less to do with building software and professional development.

Welcome. This is my own personal sprint retrospective. I use the scrum questions to reflect on my week and make notes as a developer journal entry. It is one form of working in public.

What worked well?

Smartphone. I bought an unlocked android phone on amazon. I got it activated and installed a ton of apps without too much difficulty. I’m tracking all my diabetes schtuff on there now. Already it has helped me better manage my condition. I was over at friends for dinner last night and had to make some decisions on the fly. So I looked at what was on the table, plugged in some numbers, and came up with a plateful of things I could enjoy and an accurate amount of insulin I needed to inject.

Theatre. We went to a live musical theatre performance as a family. I did not expect such a release of emotion and stress. It was the first time in over 2 weeks that I have not thought about diabetes constantly during waking hours. I felt so much better afterward. There is a place for the arts in my life.

.Net Core 3 SDK Preview. One morning I fired up an ubuntu desktop environment (from docker) and installed the new preview release of .net core 3. I was checking out the new javascript SPA templates with authentication. The identity server features look nice but I’m still not sure about managing my react client app in visual studio with the backend api.

What could be improved?

Getting out of bed on time. My mornings are slow with checking my blood glucose levels, taking my needle, and getting motivated. Well, honestly I check my blood glucose in bed because it is easier to test with warm hands (circulation for the finger pricking). While I’m doing it I listen to the news then write in my notebook. I need to shuffle some things around so that it doesn’t take me 30 min to get out of bed.

What will I commit to doing in the next sprint?

Adjusted Morning Routine. Get out of bed at 06.30. Check the furnace and the house. Fill up my water bottle. Shower/Shave/Dress. 07.00 Start making breakfast. Check Blood Glucose and inject insulin while breakfast is cooking. 07.30 start personal/professional development time. 09.00 start day job.

Post a Blog Article. I want to share my docker compose file for serving a react client app, .net core backend api, and reverse proxy server each in a separate docker container.

My Diabetes Diagnosis Story

During the past 2 months I’ve lost 30lbs fat and muscle. My thirst has been insatiable – at least a gallon of water per day. Plus anything else I can get my hands on. Juice, pop, milk.

Monday of this week I had a doctor appointment to discuss these abnormalities. She instantly knew that I’m diabetic. These are pretty typical symptoms.

Tuesday morning I did fasting lab tests. That afternoon the doctor called me in a panic asking me if I was feeling okay or if I need to go to the hospital. She said I’ve been badly diabetic for at least 3 months. She kept asking me if I’m feeling okay and said my lab results are “ridiculous”.

Wednesday I spent 2 hours at the diabetes clinic getting needles and insulin.

Thursday my levels started to come down.

Friday I went to the hospital to see an internist. To get an official diagnosis on the type of diabetes I’m being referred to an endocrinologist in a nearby city. The internist said it looks more like type 1 than type 2. For now I’m informally referring to it as type 1.5 or cryptic type 1.

Today I feel so much better.

As I look back I realize some of the symptoms started much earlier – maybe even a year ago or more and have been smouldering. Like the severe headaches in the night after exercising – probably hypoglycemic. Blurred vision – I thought I needed new glasses. Other stuff I reasoned was just me getting older or not being well.

Welcome. This is my own personal sprint retrospective. I use the scrum questions to reflect on my week and make notes as a developer journal entry. It is one form of working in public.

What now?

This isn’t a typical weekly review. My life was turned upside down this week.

Since Tuesday night I’ve had interrupted sleep at night due to stress (and a sick kid). When I get out of bed in the morning I’m checking blood glucose levels and injecting insulin. Then I need to eat fairly soon afterwards.

I believe that I can get back to my usual morning routine in time. For now, I’m on a steep learning curve and I’m forgiving myself for not achieving my weekly goals.

What will I commit to doing in the next sprint?

Adjusted Morning Routine. Get out of bed at 06.30. Go downstairs. Check the furnace and the house. Fill up my water bottle. Come back upstairs. Check Blood Glucose and inject insulin. Shower/Shave/Dress. 07.15 Make a quality breakfast. (2 eggs fried in 1 tsp of olive oil). 07.30 start personal/professional development time. 08.30 go for a brief walk. 09.00 start day job.

Buy a smartphone. As some of you know I’m a digital minimalist. I haven’t owned a mobile phone for 5 years. It has been wonderful. When people ask how I manage I tell them “it is like camping all the time.” However, I think the benefits for a diabetic having an internet connected device on your person are tangible. It seems like an insulin pump is in my near future. A continuous glucose monitor(CGM) will accompany that. When paired with a smartphone a CGM can send alerts to others when my blood sugar drops to a dangerous level (for example, if I have an episode while cutting firewood alone at the back of the property). In the meantime, I’m fielding a few calls from specialist offices for appointments and check-ins with the diabetes nurse. It is very important to me that these calls reach me (previously, I think it is fair to say that not a single phone call I received was terribly important to me).

Try a Daily Afternoon Nap

How much of my life is influenced by the weather? A lot.

We’ve had a few sunny days. The snow is melting. For a few minutes each day it is a hint of spring. I feel hope well up inside me.

Recovering from a cold has kept me down a bit. Or maybe I’m just living life at a reasonable pace. After the kids are in bed at 20.00 I’ve spent time reading by the fireplace. It feels so good.

Secretly, I desire to use that time to work on a software project or a blog article. But my eyes are sore from a full day staring at the screen. They need a break.

Welcome. This is my own personal sprint retrospective. I use the scrum questions to reflect on my week and make notes as a developer journal entry. It is one form of working in public.

What worked well?

Exercise. There is still snow on the ground and it is cold. so I didn’t do much farm work outside during exercise time. However, I found an cool resource. It’s simple and free. Nick Janvier, the site owner, has impressive progress pics. The hardest part of working out is doing it. And then keeping doing it. Other than that I don’t think it matters as much what you are doing for exercise unless you’re trying to get professional results. Working out is the hardest goal that I’m building in my life. I’m not taking it fast – moving gradually.

Consistency. I’m still getting up at 0630 and doing my daily practice in the morning before work.

What could be improved?

Code Challenges (aka HackerRank Interview Problems). As these get more difficult they take more time. I’ve spent way too much time on them this week. It was suppose to take 10-20 minutes but I’ve been spending over an hour on one problem some days (including solution evaluation afterwards). I only have 90 minutes total (from 0700 to 0830). It is not sustainable for me to do this every day.

Blog Article. I haven’t written anything substantially technical in months. I have something stirring in my mind. About how I deploy a React app with .NET API using docker. It’s coming. I find the javascript support in visual studio not to my preferences, at least when it is an integrated project javascript/C#. Same thing with jetbrains rider. Anyway, I’ll save it for the article.

What will I commit to doing in the next sprint?

Daily Code Challenges. I would still like to solve one problem per day. I plan to move this activity into my working hours, 0900 before morning meetings. I believe that is fair since it results in sharpening my skills for my employer. Frequently I’ll do something like grab an algorithm book and brush up on sorting while working out a problem. I will solve 5 problems this coming week.

Incidentally, I stole idea from Ali Spittel. She talks about it on the egghead podcast

Daily Afternoon Nap. This is something new I want to try for a week. I read about it in Tim Ferriss’s book, Tools of Titans. There is a bodybuilder in there who takes a nap every afternoon. It got me thinking about how I have some days where I get fatigued during the day. I spend 8 hours in bed every night (22.30 – 06.30) but, according to my fitbit, I only get about 7 hours of sleep sometimes less. I will nap from 14.00 – 14.30. My wife goes to pick up the kids from school at this time so the house is always quiet.

Blog Article. Moving my daily code challenges to 0900 will free up my 0700 time to start working on a new article.

Multidimensional Arrays in C#

Yesterday I was working with arrays and got hung up on a basic error message, a couple of them.

Object of type 'System.Int32[,]' cannot be converted to type 'System.Int32[][]
Cannot convert from an int[,] to an int[][]

There was not much on the internet that direct hit on these error strings (maybe it is too easy). Because of my java background it tripped me up for a few minutes.

Declaring a multidimensional array is not the same in C# as it is in Java.

//valid java, not valid in c#
int[][] array = new int[6][6];

In c# there are multidimensional arrays (think “matrix”) and jagged arrays (think “array of arrays”).

Multidimensional Array. Key points: simpler syntax but slower (more overhead). 2nd dimension the same length for all.

new int[6,6] {{-1, -1, 0, -9, -2, -2 },
{ -2, -1, -6, -8, -2, -5 },
{ -1, -1, -1, -2, -3, -4 },
{ -1, -9, -2, -4, -4, -5 },
{ -7, -3, -3, -2, -9, -9 },
{ -1, -3, -1, -2, -4, -5 } }

Jagged Array. 2nd dimension length can vary.

new int[6][] {new int[6] {-1, -1, 0, -9, -2, -2 },
new int[6] { -2, -1, -6, -8, -2, -5 },
new int[6] { -1, -1, -1, -2, -3, -4 },
new int[6] { -1, -9, -2, -4, -4, -5 },
new int[6] { -7, -3, -3, -2, -9, -9 },
new int[6] { -1, -3, -1, -2, -4, -5 } }

Once you realize this not-so-subtle difference there are lots of resources on the web available.

Resources

https://stackoverflow.com/questions/4648914/why-we-have-both-jagged-array-and-multidimensional-array

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays

Practicing More Interview Problems

It started last Saturday afternoon with the wind. Terrible, terrifying wind. I have to get some trees topped this summer so that nothing is within range of falling on the house.

On Sunday came the snow storm. The snow kept falling and falling – probably 15″ in total that day. Snow doesn’t really bother me on the farm. The tractor makes short work of it. It is kind of fun the first day but it became a distraction from my morning practice. I used that time getting the cars dug out and the driveway cleared before school (then cancelled).

Two more snow storms came during the course of the week – another 10″ of snow. And I caught a cold mid-week. The hardest part was driving over to clear my parents driveway. They live on a dead-end street that was barely ploughed. No place to put that much snow really. And I had to hand dig them out with a shovel 3 times.

Welcome. This is my own personal sprint retrospective. I use the scrum questions to reflect on my week and make notes as a developer journal entry. It is one form of working in public.

What worked well?

Practicing HackerRank Interview Questions. I’m going to put this in my needs improvement section as well. But I did complete 4 HackerRank problems and post the solutions to my GitHub account. Missed Monday due to snow.

Exercise. I had a goal to go swimming for exercise this week. It didn’t happen. The pool was even closed for a few days due to the snow storms. However, I got a quite a workout shovelling snow several times this week.

I had an epiphone with regards to exercise this week. People go to gyms to simulate hard work (lifting heavy things, getting your heart rate up). I have all the hard work I can handle on the farm. I just need to break it up into 1h – 1.5h chunks so I can do it during the lunch time slot MWF that I’ve allocated for exercise. So that is when I plan to do all my firewood cutting and storm cleanup this spring.

Crush It Audiobook. I listened to Gary V’s entire audiobook while shoveling snow this week. Good time. Good reminders to invest effort in personal branding.

What could be improved?

HackerRank Interview Problems. I did a HackerRank test this week for a job opportunity. There were 3 problems to solve in 1 hour. My solutions are good. I always take a simple, understandable approach. Nothing fancy like squeezing it all into a one line python solution that no one can decipher. The problem is that I’m painfully slow. From reading/understanding the problem to coding it up. I feel like a turtle. Anyway, on the test I didn’t finish the 3rd problem. I submitted a solution but it didn’t pass all the tests. There was a bug. Consequently, no job offer at this time.

What will I commit to doing in the next sprint?

Practice Hackerrank Problems. I will solve one problem per day on HackerRank. Specifically from the 69 Interview Preparation problem set. I will post the solution to Github.

Working in public. I’m going to put my pet project on Github (if I can find an appropriate license).

Excercise. 3 Times this week. MWF. Inside at the pool or a gym only if the weather isn’t good enough to work outside on the farm.

Practicing For Technical Interviews

Life on the farm isn’t always easy. I had a backhoe break down this week in freezing temperatures (-10C/14F). I really wanted it running so that I could clear snow. Plus it is in a location where it blocks me from getting another tractor out for the task.

I spent hours outside in the cold working on it. 2 hours in the morning before work. 3 hours in the evening after the kids are in bed. A few days of that is draining. Touching freezing cold metal outdoors is not fun.

It obliterated my daily practice and my evening reading/thinking time.

Finally after I exhausted myself I called a heavy duty mechanic. He came on Wednesday afternoon.

Thursday morning I got back on the path.

Today is Saturday and the machine still isn’t fixed.

Welcome. This is my own personal sprint retrospective. I use the scrum questions to reflect on my week and make notes as a developer journal entry. It is one form of working in public.

What worked well?

Getting up at 6:30am. Even on Saturday. Most days it is tough. My alarm goes off across the room. I get up, shut it off, stand there for a few minutes and think about going back to bed. I decide to light the wood stove then go back to bed. I go downstairs and check the thermostat. It is 57F inside the house. I get the wood furnace going, go back upstairs and stop in the bathroom. My clothes are laid out. I’m cold. I decide to have a shower to warm up. When I get out of the shower I’m on the path.

Unit Testing Refresher. I went through some basics on unit testing with xunit. I set up some simple projects in Visual Studio, Jetbrains Rider, and with the command line and added unit tests. Found an cool way to structure unit tests. Working on a big code base every day I don’t often get to start something from scratch.

James Clear ebook. I listened to most of it (within 30 minutes of the end). I will finish it today. There are a lot of good strategies in there. To me it seems like a menu of things to try rather than a howto manual. I will listen to it again to improve my retention.

Exercise. I went swimming yesterday at lunch time. It was Friday and the roads were snowy. I wanted to stay in the house very badly. I went for the soul reason that I said I would in my developer journal entry last week.

What could be improved?

Job interviewing. I’ve had a few opportunities pop up in the last couple of weeks and I’m open to a new project although not actively searching. However, I haven’t done a job interview in 5 years. It has changed. There is a whole new industry out there of testing services that rank your solution and pass it to a a prospective employer as a score out of 100. In my professional life I don’t often program how many candies Alice (the teacher) is going to share with each student in her class based on merit. So although my experience is good and I present myself well I need some practice on solving these tricky little problems.

Working in public. As much as I want to share what I’m doing it isn’t natural for me. For example, I don’t think of tweets to send out every day. It is not that I don’t have something technical to share. Twitter just isn’t on my mind. Most of the time it isn’t open on my developer workstation.

What will I commit to doing in the next sprint?

Practice HackerRank Problems. I will solve one problem per day on HackerRank. Specifically from the 69 Interview Preparation problem set.

Post to Github. I will put each of my HackerRank solutions on Github for the world to see.

Go swimming again. Honestly, I would have counted it a victory just making to the swimming pool (so would James Clear). But I got changed and went in the pool. Swimming was really tiring. I did 12 lengths in poor form then went and sat in the hottub for 10 minutes. But I felt really good afterwards. Worth repeating.

My Very First Developer Journal Entry

Every morning I get up at 6:30am, light the wood furnace, shower/shave, fry two eggs, and sit down at my desk. It is still dark out. The old farmhouse is cool and quiet.

This is my daily practice.

I spend 90 minutes exploring new technologies, enhancing my skills, working through courses, building personal projects, anything I can do to improve myself as a software engineer.

I should write about it more but I don’t. Perhaps this will change in 2019.

To this end I’m using the scrum retrospective questions to reflect on my week and make notes as a developer journal entry. We’ll see if public accountability helps.

What worked well?

Coaching call. Yes I have a coach I talk to once per month. It keeps me on track with everything from time management to priorities to personal branding and marketing. I believe I originally got the desire from listening to Noah Kagan. If something is important enough to you it is worth hiring a coach. This journal entry is an outcome of my coaching call.

Progress on Market Garden Manager. One of my personal projects is a crop planning tool for serious vegetable gardeners. It is primarily to meet our needs but someday maybe someone else would like to use it as well. It has been on a shelf for a few months. This week I dusted it off and got to work on it.

Persistence on javascript type errors. Not much to explain here. Just that I slogged through several hours of javacript errors this week. By sticking with it and coming back each morning I learned a lot.

Daily review in my notebook. Also a suggestion from my coaching call. Each night I take a page in my little notebook and write down “What did I accomplish today?” and “What am I going to accomplish tomorrow?”. It is specific to my personal/professional development. If this journal entry is my sprint retrospective then I guess you could call my nightly review the scrum equivalent of my own personal daily standup meeting. Except I’m sitting down – usually on the edge of my bed.

What could be improved?

Giving a book away on twitter. I offered a book up on twitter as a giveaway. I even offered to pay shipping to anywhere in North America. Why? I’ve gone through it already and now it just gathers dust on my shelf. It is starting to get a little older and I thought someone could get some benefit from it before recycling. After all it is still $47 on amazon.com. Not a single person responded. That’s fine. My friend said he wanted it. Don’t know if I’ll try that again. The book: Dependency Injection in .NET by Mark Seeman.

Exercise. I dropped some team sports at the end of 2018 in order to have more time and energy for personal/professional development. The justification was that I would spend my lunch hour doing some sort of physical activity and get to bed earlier at night. It is only half-working. I’m going to sleep at 10:30pm but I’m still am not taking a lunch break from work unless I have an appointment to go to.

What will I commit to doing in the next Sprint?

Listen to James Clear Atomic Habits audio book. I bought it on audible this morning. I’ve heard a few people raving about it. I commit to listen to it once before the next sprint.

Go Swimming. I will go lap swimming at the pool one day this week during my lunch break (I promise to take a lunch break from work that day).

C# Is Dangerous

I was asked why C# is still relevant in 2018. What makes a language relevant to me? Someone pays me to work on it. Preferably a lot of money. With that there is this risk reward of developing rare skills. To me Cobol is relevant in 2018. A few people make a lot of money maintaining Cobol systems. However, (at least where I live) I don’t see a lot of ads for Cobol developers. I see a bunch of C# ads and a ton for Javascript developers. You need to seek the balance between valuable skills and available work.

Within a few days another friend asked me what programming language to learn as a first language in 2018. You might think I would suggest C#, but I didn’t. The truth is, as a professional software engineer I have little affinity for C#. I’ve written some articles on C# tooling because that’s what I look at day in and day out. But I would also be happy and very effective working in another language.

Building software is a bit like building houses. Take a builder who does brick houses vs one who does wood framing. Each material has strengths. Brick is fireproof. Wood withstands earthquakes. Each has regions of better pricing and availability. A superior builder knows building systems and when to use each material. Can a builder switch from building brick houses to wood-framed houses? A professional builder should be able to switch with time and study. The underlying building principles remain constant. But the materials, tooling, and techniques are different. Switching could take some trial and error.

Superior software engineers know principles over languages. GRASP Patterns. SOLID Principles. These do not change from language to language.

Now to the heart of the matter. Microsoft tries hard to reduce workload for developers. You click on new project in visual studio, select a template, and immediately you have a working web application with a database and everything. If this is your introduction to software development then you are building your software engineering base on sandy ground. For example, you will see dependency injection introduced by the template but not necessarily understand how it is working and why it is important. Without a proper foundation an IDE is a crutch as much as a tool.

This is why C# is dangerous. The Microsoft tooling makes it easy for inexperienced developers to build poor software. And this problem is not exclusive to C# but I worry that is it more prevalent with C# (and Visual Basic.NET).

C# as a relevant language in 2018 is not in question. It has any feature available that I’ve come to expect. Like a building system (think brick vs wood) some of these are better in C# and some are better in other languages. All of these are available in most languages but no language that I’ve found is perfect.

Openness / portability – Free. Cross-platform. Open source. Public design reviews. Weekly open calls. (contrast this to the new commercial licensing for java)

Modern language constructs– generics/ lambda expressions / anonymous functions / delegates. The list goes on and the specification evolves regularly. Microsoft hires some really smart people to oversee this.

Package management – NuGet. So convenient for software re-use. Integral to dotnet core.

Great libraries – well-documented, reliable, mostly open-source, and clean. Anything I need to do I can find a package and easily reference it.

Supported by cloud infrastructure – There are lots of different ways to host your application in the cloud. PAAS options on azure. Or container-based solutions using docker on pretty much any host (e.g. digital ocean droplets).

CSharp Side Hustle – Set Up Your Project And Git Repository

Where do we start? At the beginning. The very beginning. This material is so basic I almost skipped over it. But … there are some very explicit reasons why you set up your CSharp project and git repository for a side hustle project in this manner. And specific reasons why you choose certain tools. This is the first step to creating a web application using Angular ASP DotNet with Authentication. Basic flow shown in the video. More explanation in the article below.

As a reminder, a side hustle project should be a line of business application (do not try building the next facebook or re-inventing email). A side hustle project should be bootstrapped and self-sustaining.

Keep your side hustle project as simple as possible: one visual studio solution, one docker image, one git repository, one host. Do not over-complicate your web application prematurely. You will have several months of low traffic before you need to scale.

Overall Architecture – Javascript SPA (Angular) + Web API Back End (ASP DotNet Core) + PostgreSQL database via Entity Framework Core. There are some newer frameworks available, but for a side hustle new technology is a project killer. Stick to what you know. In my case Angular is well-supported in dotnet and is what I have the most experience with.

Install Tooling

Microsoft Visual Studio Community 2017 – Sign up for the free developer account, Visual Studio Dev Essentials. It seems the trend is away from Visual Studio in ASP DotNet Core project tutorials. I do not know why. Maybe the emphasis is on the cross-platformability of DotNet core. But the vast majority of DotNet developers are working in Windows. Visual Studio Community is free for individual developers. It has a much richer feature set than Visual Studio Code. Use it.

Notepad++ – It will save you the hassle of learning VI to write your commit messages for git.

Git for Windows – There is a git plugin with Visual Studio. Don’t do it. Learn git the way it was designed to be used … on the command-line. When installing accept all the defaults except for text editor. Select Notepad++. Thank me later.

Tortoise Git – nice for visualization. I use it for repository browsing only.

Scaffold Project from Template

You want Angular + Docker + Authentication. There is no perfect project template so it becomes a question of which project template will allow the least amount of manual grunt work.

  • Web API Template with Docker Support – we could use this one.
  • Angular SPA Template (without Docker Support) – this is probably the least work. It is easy to add docker files afterwards.
  • ASP DotNet MVC with Authentication – not really that helpful since it uses ASP DotNet Core Identity. In my experience I haven’t seen this working with an Angular client so I plan on using Identity Server.

Create Remote Repository and Push

This may be an unnecessary step for you. Since you’re only one person working on a side hustle project there is no need to coordinate or merge changes. You can do version management with a local git repository. The only thing you get from pushing to a remote repository is offsite backup – for the moment (in the future automated builds). So if you’ve got a rock solid backup mechanism in place maybe you want to keep your code in a local git repository.

Visual Studio Team Services – Free private git repositories as part of Visual Studio Dev Essentials. To be honest I use a self-hosted gerrit instance at work. I’m trying out the git repositories on VSTS for private code hosting. But Git is definitely the tool you want to know for managing your source code – especially since Microsoft Bought Git Hub. Why not use GitHub? Of course I agree GitHub is the fountain of all goodness. But … it costs $7/month for a private repository. When your project is earning $7/month you can choose to spend it on GitHub source code hosting. In the meantime use a free option since there is one available.

Conclusion

Keep it simple. There are so many ways that you could make this more complex than it needs to be. I’ve seen projects that separate the javascript client from the backend api. Different repository and different hosts, cross-origin requests (look that one up). Docker makes that more doable and maybe you will end up there with your side hustle project over time. But for now don’t over complicate things.

Opt for free over paid when the functionality is equivalent. Even if it is less cool. I know exactly zero individual devs who put their code in a git repository at VSTS for side hustle projects. Or who would rather be trying JetBrains Rider instead of Visual Studio Community? Keep your project self-sustaining.

In the next article we’re going to set up the project for docker support and hook up the database to back some web api calls.

Setup PostgreSQL with Docker for Your C# Database

Time to set up your database for your C# side hustle application. Stick to what you know. For most of us coming from a corporate environment we know SQL Server. But it is better to avoid SQL Server for side hustle applications because the license fees are so high.

The next best database at this time for C# applications on Entity Framework is PostgreSQL. It is feature-rich, mature, and well-supported in terms of the database itself and the entity framework providers.

Setting up your PostgreSQL Database Server in Docker

My preference is to spin it up in docker. Why? It’s temporary. Changeable. Simple version management and upgrades. Easy production setup.

Aside: One thing I’ve seen lately that I strongly want to discourage – creating custom builds of application docker images for the only purpose copying over configuration files. Don’t do that. It is unnecessary work and complexity. Use a volume with a mount to keep any configuration you need on the docker host. It makes configuration changes simpler and it is easier to manage the overall solution in a docker compose file(think many containers). I will show you how to do this.

You will probably want to spin up your development PostgreSQL docker container manually. There are two ways to persist your PostgreSQL data on the host machine: Volumes or Bind Mounts. If you’re on a Windows host then you definitely should use volumes since they are managed by Docker, not dependent on the host directory structure, and have consistent behaviour on Windows and Linux hosts. Even on any docker host, volumes have many advantages over bind mounts. However, in my experience bind mounts have been around longer and are more common.

Note: You will have problems if you start the PostgreSQL container with a Bind Mount on a Windows host. Read this article for more details. Deploy to a linux docker host in production.

So first create the volume:

docker volume create postgresql-volume

You can then use docker volume commands inspect or manipulate the volume:

docker volume ls
docker volume inspect <volume-name>
docker volume rm <volume-name>

Docker Volume Commands

 

Now you can spin your your postgresql container referencing the forementioned volume, postgresql-volume.

docker run -p 5432:5432 --name postgresql -e POSTGRES_PASSWORD=password -d -v 'postgresql-volume:/var/lib/postgresql/data' postgres:10.4

Note: It is a good idea to manage the version of the container you are running. Simply omitting the container version or using latest each time could cause unanticipated changes.

Connect to the command-line management interface on your docker container (to exit afterwards type ‘\q’).

docker exec -it postgresql psql -U postgres

For more details about using psql watch this video: https://www.youtube.com/watch?v=A8dErdDMqb0

docker run -p 5432:5432 –name MarketGardenManagerDB -e POSTGRES_PASSWORD=password -d -v ‘C:/Users/gmccallum/source/MarketGardenManager/db:/var/lib/postgresql/data’ postgres:10.4

Due to a limitation with the postgres docker container have to use a docker volume(above) instead of a volume mapping (below). Reference: http://www.lukaszewczak.com/2016/09/run-postgresql-using-docker-with.html

For development I like to keep my database data files in the project folder. Then they are closer at hand to blow them away if you want to re-create from scratch and refresh the container.

It is worth noting the different paradigm here. Infrastructure as code. Before the first push to production all the docker container details will be in the docker compose file and checked into a git repository. Any change to the server configuration is tracked with version control. My SQL Server server instances at my day job are set up and and maintained for as long as possible. Static versus transient. With docker containers you can easily rebuild the server from scratch every time there is a deployment.

Setup your PostgreSQL Administration Tool (in Docker)

The PostgreSQL equivalent of SQL Server Management Studio is pgAdmin. It is a web-based tool. There is a windows installer that runs it on a web server locally for you. Or .. you can do what I do … simply spin up the docker container.

Before starting the container ensure that that path to your configuration directory exists (C:/Users/gmccallum/.pgadmin). Then run the command to download and start the container:

docker run -p 8080:80 --name pgAdmin -v "C:/Users/gmccallum/.pgadmin:/var/lib/pgadmin" -e "PGADMIN_DEFAULT_EMAIL=glen.mccallum@protonmail.com" -e "PGADMIN_DEFAULT_PASSWORD=password" -d dpage/pgadmin4

Note: After what I said above about Volumes being better than Bind Mounts … I went and used a Bind Mount for the pgadmin data folder. Old habits die hard. I will switch this to be a Volume for permanent use.

Open it up in your browser at http://localhost:8080. Since this is run locally for you on your dev machine only you can skip the SSL certifcate and https configuration. However, if you plan on accessing this tool over a network (or the internet) see the notes on the docker hub page for further details.

pgAdmin Welcome Screen

 

By default docker containers run in bridged networking mode. So when you’re connecting from your pgAdmin container to your postgresql container you have to either connect to the host on the mapped port 5432. Or you can connect to the postrgresql container directly on port 5432. Considering the possible-transient nature of the IP address on your host machine I would consider connecting from container to container directly.

Connect to your PostgreSQL instance by right clicking on ‘Servers’ in the left pain, then ‘Create>’, ‘Server…’.

You can get the IP address of the postgresql container by using the inspect command from your host. Then scroll to the bottom and find the ip address.

docker inspect postgresql

Docker Inspect Container

Then use that IP from the pgAdmin Create Server interface and the password from above when you spun up the postresql container (‘postgres’ is the default username).

pgAdmin To Container Connection

 

To start and stop the pgAdmin container (my equivalent to opening and closing an application) just run:

docker start pgAdmin
docker stop pgAdmin

Connect to PostgreSQL From your C# Application

Wes Doyle has an awesome video on how to do this. I dunno how he does the whole thing in one take with zero mistakes. I do it the exact same way.

appsettings.json

"ConnectionStrings": {
"MyConnectionString": "User ID=postgres;Password=password;Server=localhost;Port=5432;Database=MyDatabase"
},

Startup.ConfigureServices

services.AddDbContext(
                options => options.UseNpgsql(Configuration.GetConnectionString("MyConnectionString")),
                    ServiceLifetime.Scoped);