Focus and avoid context switching

My day job as a software engineer requires a great deal of focus and organization. Writing code is one of the last steps you do in software development. Writing code only comes after gathering enough information and understanding what changes or features we need in an application.

Focusing on one task, but more importantly, one project at a time is critical. When working on more than one project at a time, there is a lot of context switching, which is terrible for you and your productivity.

Focusing on one task also allows you to fully immerse into the details of the project, expand your domain knowledge about the work area, and as a result, be thoughtful about the way you approach the project, its problems, and the solutions.

Context switching while doing any work that requires concentration decreases the project’s opportunity to succeed and your productivity as well. The result is a net negative, and I don’t see any reason to do it. The only reason we do it might be due to our inability to focus on one task or the constant interruptions that are common in the workplace.

Focusing today is more challenging than ever. We have many tools around us that trick us and push us to pursue distractions. The handheld devices we all have are the number one reason for this, in my opinion. These devices are the window into a lot of addictive content out there, and trying to stay focus while having these devices next to us requires a lot of discipline.

It’s not all our fault. We are the victims of advanced algorithms that know us well and learn how to get our attention. It takes a lot to turn off notifications and not open our favorite apps to see the latest micro-piece of content. But, it’s a very effective drug that works against us.

Of course, there are simple ways to minimize this. I, for example, have most of my notifications off. The only place where I turn notifications on is on my family chat. Other than that, I never get pulled in by an app since I don’t get notified about anything. So that works, but just a little.

There are other things I do to keep myself focused and stick to one task at a time. For example, I set up specific times (timeboxing) to do the other distracting tasks such as checking email, social media, the news, etc. I timebox these tasks and try hard not to allow myself to break that rule.

Timeboxing helps a lot. In the past, I spent a lot of time checking, reading, and replying to emails. Nowadays, I check email maybe once a day, and I do not respond to emails unless strictly necessary. I do the same for social media apps, and if you use an iPhone, the Screen Time feature can help you a lot with this.

For non-digital distractions, you can also use the concept of timeboxing. For example, at work, I set up “focus time” in my calendar to make sure people know when I will be available to join a meeting and when I am not. Setting focus time in your calendar sets the expectations of other people around you. It will make it easier for them to know when you might be free to talk, have a meeting, or help with some other task.

I break my workday into four areas, the first block of time, 7-9 am is OK for meetings and open tasks, from 9-12, my time is blocked for deep/focused work, lunch from 12-1 pm, and finally from 1-4 pm I have open it up for meetings and time to reply to email and other office messaging apps.

I started doing this more than a year ago, and it works very well. I get very few if any distractions during my “focus time,” which is enough to make me productive and more relaxed. Before doing that, I checked email constantly, responded as soon as possible to any message, and accepted all meetings at any time. Unfortunately, that caused my productivity to drop considerably and, with it, my motivation and energy.

Context switching is tough for tasks that require concentration. You cannot concentrate with the endless amount of notifications coming from our devices, from people around us, and from our lacking ability to concentrate. We have to set clear boundaries with ourselves and be assertive and disciplined to make sure we and others around us respect them.

Setting limits and structures around my life is not something I often do. I prefer to live the moment, be casual with what I do in life, and allow myself to do unexpected things. However, when it comes to working, whether it is personal or professional, setting boundaries and allowing yourself to focus on tasks is a game-changer.

This advice is not only about being more productive. Focusing on tasks is also less stressful and much more enjoyable once you learn how to do it. I hope this is helpful for you, and please, if you have any other suggestions, questions, or any feedback, please let me know here in the comments. Cheers.

How to (efficiently) update millions of records in a SQL table

You need to update one or more columns in a table with millions of records with data from another table, what’s a good way of going this with low risk and in an optimized way? One of my favorite ways of dealing with millions of records in a table is processing inserts, deletes, or updates in batches.

Updating data in batches of 10,000 records at a time and using a transaction is a simple and efficient way of performing updates on millions of records. The key is to batch out your data to allow you to process a smaller number of records at a time.

Example:

use DatabaseName
go

DECLARE @batchId INT
DECLARE @batchSize INT
DECLARE @results INT

SET @results = 1
SET @batchSize = 10000
SET @batchId = 0

-- when 0 rows returned, exit the loop
WHILE (@results > 0)
	BEGIN
		BEGIN TRAN;

		UPDATE Table1 SET columnA = Table2.columnA
		FROM Table2
		INNER JOIN Table1 ON Table2.Id = Table1.Id
		WHERE Table1.columnA is null
		AND (Table2.Id > @batchId
		AND Table2.Id <= @batchId + @batchSize)

		SET @results = @@ROWCOUNT
	
		-- next batch
		SET @batchId = @batchId + @batchSize

		COMMIT TRAN;
	END

-- the sql below is just to measure the performance of this update, it is not needed to update your data.

DECLARE @startTime DATETIME

SELECT  @startTime = GETDATE()
SET STATISTICS PROFILE ON
SELECT  COUNT(*)
FROM Table1 first OPTION (RECOMPILE)
SET STATISTICS PROFILE OFF
SELECT  'It took ' + CONVERT(VARCHAR(8), DATEDIFF(ms, @startTime, GETDATE())) + ' ms'
GO

In the query above we declare the following variables to do the batching:

  • @results – this variable will hold the number of records updated; when zero, the query will stop. This is to avoid an infinite loop.
  • @batchId – this is set to zero initially, and it is used to compare the table id against it, and after each update, it is set to the id plus the batch size. This allows splitting the millions of records into batches.
  • @batchSize – the number of records to update at a time.

It is important to know that the above algorithm will only work when your table’s primary keys are of type int. If your table’s primary keys are guids, the above will not work.

The section at the end of the query is only used to review the performance of your updates, it is not necessary to update the data and it is a nice way to see how the query performs overall.

I hope the information in this post is helpful, and it helps you learn a simple way to update millions of records in batches, making it easier and lower risk than attempting to do it all at once.

Must-have VS Code Settings for Web Development

Last week I wrote about must-have VS Code extensions for web development. This time, I’m writing about the recommended settings to make sure these extensions and VS Code work correctly. 

VS Code is an
excellent tool for writing software, and when you install the right extensions, it can be very powerful. However, if these extensions and VS Code isn’t set up correctly, many of its features or extensions might not work the way you expect them to work.

Below is a list of settings that I use as my base when setting up VS Code for any type of web development. You can also get them from the gist located here:

https://gist.github.com/ricardodsanchez/179f693c8c843abc782e3e40112904aa

The way to get to the setting in VS Code is by typing Ctrl-Shift P and then type “settings”. A settings.json file will open and this is where you can remove all existing settings and paste the settings below.

{
  "telemetry.enableTelemetry": false,
  "telemetry.enableCrashReporter": false,
  "files.autoSave": "afterDelay",
  "files.associations": {
    "*.md": "markdown"
  },
  "window.zoomLevel": 0,
  "[html]": {
    "editor.defaultFormatter": "vscode.html-language-features"
  },
  "breadcrumbs.enabled": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "editor.acceptSuggestionOnEnter": "on",
  "editor.detectIndentation": false,
  "editor.fontFamily": "'Source Code Pro', Menlo, Consolas, Courier, monospace",
  "editor.fontSize": 13,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.multiCursorModifier": "ctrlCmd",
  "editor.quickSuggestions": {
    "other": true,
    "comments": true,
    "strings": true,
  },
  "editor.renderWhitespace": "none",
  "editor.snippetSuggestions": "top",
  "editor.tabSize": 2,
  "editor.wordWrap": "on",
  "editor.wrappingIndent": "indent",
  "extensions.ignoreRecommendations": true,
  "extensions.showRecommendationsOnlyOnDemand": true,
  "files.exclude": {
    "**/._*": true
  },
  "files.insertFinalNewline": true,
  "html.format.endWithNewline": true,
  "html.format.extraLiners": "body",
  "html.format.indentInnerHtml": true,
  "html.format.unformatted": "b,em,i,span,strong,wbr",
  "html.format.wrapLineLength": 0,
  "liveServer.settings.donotShowInfoMsg": true,
  "liveServer.settings.port": 0,
  "workbench.colorCustomizations": {
    "editorIndentGuide.activeBackground": "#FFA500"
  },
  "workbench.editor.tabSizing": "shrink",
  "workbench.editor.enablePreview": false,
  "workbench.editor.enablePreviewFromQuickOpen": false,
  "gitlens.advanced.messages": {
    "suppressGitDisabledWarning": true
  }
}

That’s all for all folks, remember to subscribe and please let me know if you have any comments or questions below.

Here’s one way to cure procrastination

Writing is something I enjoy doing, , but to be very candid, it is hard for me to sit down and start writing. It’s the same feeling I have about working out, for example, love the feeling while exercising and then after when I’m done, but it isn’t easy to start an exercise routine; starting is what’s difficult for me. Does that happen to you? Well, it happens to me, and one word for it is procrastination.

Procrastination is something that happens to everyone, we know we need to do certain things, but we push them to the back-burner until that decision comes to burn us one day. Why do we do this? Why do we procrastinate?

As procrastination builds, it can start to affect us severely. For example, I’ve missed several flights, hotel reservations, tax returns, and a lot of money due to this by procrastinating. Since wasting money is not enjoyable, I had to change my ways so one day I sat down and decided to do something about it – hey, at least I didn’t procrastinate on that!

The Plan

The first step of my plan involved finding and installing popular to-do apps like Todoist, Microsoft To Do, Wunderlist, etc. and while some of these apps are well designed and helpful (I still use Microsoft To Do for simple items), I continued to procrastinate. Then I tried writing these tasks using pen and paper, it didn’t work either, but at least I now own a neat journal and beautiful and inexpensive pens from Muji which I use for other things. I’ll share more about that on another post.

After these two failures, and thinking about it retrospectively, a moment of clarification appeared and a new idea was born. That process alone helped me figure out an important truth, I wasn’t giving these tasks the priority that they deserved. You see, I had it all wrong, I was attempting to create a to-do list but what I really needed was a dislike-but-still-need-to-do-it list. What’s the difference you might ask? Keep on reading dear friend, you’ll soon find out.

With this information in mind, I decided to experiment. What if I treated my other tasks with a higher priority and added them to a dislike-but-still-need-to-do-it list? The initial idea was to create this list in a spreadsheet and include a column listing the specific consequences of not getting these things done. It’s very innovative, I know.

The dislike-but-still-need-to-do-it list included items like the following:

  • Apply for the Nexus program for my kids
  • Replace car’s headlamps with new ones I already bought
  • Other personal items I do not care to list because they are for me and not for you dear reader.

These are a few items that I have been dragging for months, and I know they are important, but can’t get myself to remember them enough to do them. These items were the first ones that I added to my dislike-but-still-need-to-do-it list along with the consequences, and it looked like this:

To-doConsequences
Apply for the Nexus program for my kidsBecause if I don’t, the next time we travel to Canada we could end up waiting in line at the border for a long time as we did last time.
Replace car’s headlamps with new ones I already boughtBecause if I don’t, the driving visibility at night will not improve and then I might have to deal with more serious consequences.

Great, now I have a list of things I don’t want to do with a fearful description of what could happen if I don’t do it. Perfect? Not quite.

A better plan

While this was a bit more motivating than just have a simple to-do list, it still wasn’t enough. To keep these items top of mind, I decided to list a few benefits gained if I did these things; I am not driven by fear, so listing the consequences wasn’t enough for me.

To-doConsequencesBenefit
Apply for the Nexus program for my kidsBecause if I don’t, the next time we travel to Canada we could end up waiting in line at the border for a long time as we did last time.Reducing time by using Nexus or Global Entry kiosks when entering the United States. Saves a lot of time.
Replace car’s headlamps with new ones I already boughtBecause if I don’t, the driving visibility at night will not improve and then I might have to deal with more serious consequences.Increased night visibility.
The car looks better.
Increase car’s re-sell value.

Ta-da! At first look I was excited, I really thought I had it, in fact, just writing the benefits and negative consequences motivated me to the point I wanted to take care of these things as I was adding them to this dislike-but-still-need-to-do-it list. But after looking at it for a few minutes, I noticed something wrong, something very wrong in fact that I almost ditched the whole idea right away.

In my attempt to prioritize and motivate myself to do these things, I spent a great deal of time writing a lot of words to convince myself that this was a good idea, but it wasn’t. Some of the items in this list could have taken me only 5 minutes to complete, and instead of getting them done, I spent a great deal of time thinking and writing about the consequences and the benefits of getting them done. Fail. Big fail. Huge fail. So what now?

I really liked the list and how it made me feel, but I couldn’t possibly maintain such a to-do list with so much detail describing consequences and benefits because that wasn’t going to scale. If you want to stop procrastinating, you have to lower or remove all barriers between you and what you want to get done.

What can be changed? I asked myself, what if I removed the consequences column, shortened the contents of the benefits column, and added a due date, after all, what’s a to-do list without a due date right? After those changes, the dislike-but-still-need-to-do-it list looked like this:

To-doBenefitDue date
Apply for the Nexus program for my kidsSaves a lot of time when entering the country.2/1/2020
Replace car’s headlamps with new ones I already boughtIncreased night visibility and car’s re-sell value.2/1/2020

Finally, a to-do list that is informative and manageable. It requires enough effort that keeps items top of mind by reminding me about the benefits of getting them done. Does it work? Only time will tell. So far I have been using this version of the list for almost a month, and since then many items have been completed, it seems to be working.

Conclusion

When going through the process of creating the dislike-but-still-need-to-do-it list list I learned something about myself I didn’t know. I’m driven and motivated by the potential benefits than by fear, knowing about a positive outcome moves me more than knowing the negative consequences of not doing something. I didn’t know this about myself. The process of writing the benefits along with my to-do items takes a little more time, but this extra time is well spent as it helps me understand better the reason I need to do it.

That’s it folks, hope that my experience with my dislike-but-still-need-to-do-it list helps some of you as it helped me to cure the procrastination and get more things done. Cheers.

How to host a static website on Amazon’s AWS with SSL using S3, Certificate Manager, CloudFront, and Route53

So you have a static website and need to host it somewhere, there are many places to host your site but since you also want your site to have a security certificate, and you want all of this at a reasonable price, your options are limited.

Last year, I tried Azure Storage to host a static website, but at the time, the options to get and apply a security certificate to a site hosted on Azure storage was complicated, it was very confusing.

This time I decided to give AWS a try, and it turns out, hosting a static website using AWS’s S3 storage service works really well for static websites.

AWS also has a somewhat simple way to set up your new static website with a free security certificate. Below I will show you the steps to accomplish this.

These are the services you’ll need to configure to host your static website and an SSL certificate with Amazon’s AWS:

  • S3
  • CloudFront
  • Certificate Manager
  • Route53

The instructions below assume that you’ve already signed up for a AWS account.

S3 – Create and change the properties of your static website bucket

After you login to your AWS Console, search for S3 and create a new bucket for your static website. When creating the new bucket, you only need to give it a unique name, and then uncheck the Block all public access options under permissions. Don’t change any of the other default values or options.

Properties tab

After you’ve created a new bucket to hold your website files, click on the bucket name and then on the properties tab. From here, select the Static Website Hosting, it should look like the screenshot below.

In this window, you want to put the name of your main page (i.e. index.html), an optional error page, and any redirection rules, also optional.

Image of static website hosting properties in AWS S3

Before you move on to the next step, copy the Endpoint value from the Static website hosting window and save it, you’ll need it for the CloudFront Distribution section below. In the example above, the endpoint is the URL: http://solopractica.s3-website-us-west-2.amazonaws.com

Permissions tab

Make sure the Block all public access option is unchecked. Now go to the Bucket Policy option and click on Policy Generator.

Select the options as shown above, make sure the Amazon Resource Name (ARN) follows this format: arn:aws:s3:::YourBucketName/* and replace YourBucketName with the actual name of your newly created bucket.

Finally, click on Add Statement and then Generate Policy, a new window will open with your new bucket policy in JSON format. Copy the JSON document, and paste it into the Bucket Policy space back in the bucket properties page.

If you get the following error message after saving the new policy: Policy has invalid resource, make sure the bucket name value is correct, and save again.

You’ll see a warning informing you that your bucket has public access, that is fine, the bucket needs public access to host your static website.

CloudFront Distribution – Create and configure

A CloudFront distribution is required if you want to host a static site and distribute media files using HTTP or HTTPS.

To create a CloudFront distribution, go to the AWS console, and type CloudFront in the search box. When the CloudFront Service page opens, click on Create Distribution, and then select Get Started for the Web option.

CloudFront distribution properties

Do not be overwhelmed by the many options in this window, you only need to change a few of these properties. Below are basic instructions on how to fill out the Create Distribution form.

Origin Settings

  • Origin Domain Name: Select your bucket endpoint from this list.
  • Origin Path: Leave it blank.
  • Origin ID: It gets filled automatically when you select the origin domain name above.
  • Restrict Bucket Access: No.
  • Origin Custom Headers: Leave default/blank values.

Default Cache Behavior Settings

  • Path Pattern: Nothing to change here.
  • Viewer Protocol Policy: Redirect HTTP to HTTPS (but you can select any option, it is up to you).
  • Allowed HTTP Methods: GET, HEAD.
  • Field-level Encryption Config: Leave default/blank value.
  • Cached HTTP Methods: Leave default value.
  • Cache Based on Selected Request Headers: None.
  • Object Caching: Use Origin Cache Headers.
  • Minimum TTL: Leave default.
  • Maximum TTL: Leave default.
  • Default TTL: Leave default.
  • Forward Cookies: None.
  • Query String Forwarding and Caching: None.
  • Smooth Streaming: No.
  • Restrict Viewer Access: No.
  • Compress Objects Automatically: No.
  • Lambda Function Associations: Leave default/blank value.

Distribution Settings

  • Price Class: Use Only U.S., Canada and Europe (the cost of it will change based on what you select here. Click on the information icon next to this setting and make the right choice for you).
  • AWS WAF Web ACL: None.
  • Alternate Domain Names (CNAMEs): Type your domain name and any subdomains you have for the bucket hosting your static website. For example, for my site solopractica.com, I entered the following values here:
    solopractica.com
    http://www.solopractica.com
  • SSL Certificate: Custom SSL Certificate. This is where you’ll also be clicking on Request or Import a Certificate with ACM (see section below).
  • Supported HTTP Versions: HTTP/2, HTTP/1.1, HTTP/1.0
  • Logging: Off
  • Enable IPv6: Checked.
  • Distribution State: Enabled.

After you request a SSL certificate and complete all of the options, click on Create Distribution.

Certificate Manager – Request a Certificate

From the steps above, open up the window to request a new certificate by clicking on Request or Import a Certificate with ACM.

In this page, type your domain name and www version of it and then click Next. Example:

Select validation method

Choose the DNS validation option, it’s the fastest and easiest. If you don’t have access to your domain DNS settings, then you can try Email validation instead. Click Review, and then Confirm and request.

Validation

Once you go through the steps to validate your domain(s), you’ll see a window with your Request in progress and the instructions to add a CNAME record to the DNS configuration for your domain. Click Continue.

Certificates

This page will show the status of your certificate request, you can refresh the status of your request to get the status updated. The time to get your domain verified depends in part, on your domain registrar.

After your certificate has been approved, go back to your Distribution and click on it to edit it. From the edit page, make sure you have the Custom SSL Certificate option selected and then select your brand new SSL certificate from the list.

Route 53 – Create and configure

This is the last step, it will allow AWS to route your domain name and certificate to the appropriate resource.

Go to the AWS console and type Route 53 in the search box, click on the Route 53 link, and then on Hosted zones.

Hosted zones

Create a new hosted zone, enter your domain name, make sure the Public Hosted Zone is selected and click Create.

Record Sets

Two record sets are created by default when creating a new zone, a NS (Name Server), and SOA (Start of authority).

While selecting the newly created Hosted Zone, click on Create Record Set.

Use the following settings and values when creating the new record set:

  • Name: Leave the name box empty.
  • Type: A – IPv4 address.
  • Alias: Yes.
  • Alias Target: Select it from the list, you should see a value available if all of the steps above were completed successfully.
  • Routing Policy: Simple.
  • Evaluate Target Health: No.

After this, you can add another record set of type A for any additional domain names you might be using, for example, http://www.yourdomain.com.

That’s it, by now you should be able to open your browser and go to your domain, it should be available with the https protocol.

Cheers!