Advent of Code 2020

I can’t believe that I forgot to post about the 2020 Advent of Code until just now! Man I suck, but in truth, I have been a bit busy with my new gig.

There didn’t seem to be a puzzle this year that they kept building on like in years past. I actually kind of liked those kinds of challenges, but I will say that the 2020 set of challenges were fun to work on.

Please check out my Advent of Code Github repository:

https://github.com/Wave39/AdventOfCode

420 years of ignoring Windows Updates

Some people wait a very long time, if ever, to do their Windows Updates. (For better or worse. Seriously people, run your Windows Updates.)

But this is a bit ridiculous…

Windows Update

BTW, Happy Birthday to the National Baseball Hall of Fame, opened this day in 1939 in Cooperstown, New York. I sure wish we had baseball right about now…

Migrating AFNetworking to NSURLSession

I have some legacy Objective-C code that I want to bring up to the latest iOS code. Part of this is migrating AFNetworking to NSURLSession.

Not that I have anything against AFNetworking of course, I have used it for a very long time, especially when the communications capabilities in the Foundation framework were a bit more primitive than they are now. I have just been trying to reduce dependencies in my projects where I can, and for my communications needs, the newer Foundation classes give me the same kind of ease of use that AFNetworking has.

For example, here is a simple example of some of the legacy code that I have in the app:

NSURL *url = [NSURL URLWithString:@"http://link.to.the.site.you.are.loading"];    
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    // do something with the operation.responseString
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // an error occurred
}];    
[op start];

And here is what it looks like when you migrate to NSURLSessionDataTask:

NSURL *url = [NSURL URLWithString:@"http://link.to.the.site.you.are.loading"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error != nil)
        {
            // an error occurred
        }
        else
        {
            // do something with the data
        }
    });
}];
[task resume];

All in all, I think that 7 years of usage (I migrated to AFNetworking in 2013 as described in the post Migrating ASIHTTPRequest to AFNetworking) is pretty good for using a library. Kudos to the team maintaining that library, I do not know if I would have the patience to stick with it for that long.

BTW, Happy Birthday to John Myung, bass player for Dream Theater.

Advent of Code 2019

The calendar is about to turn, which can only mean one thing. Time to finish Advent of Code!

I stumbled a bit on some of this year’s puzzles, as it seemed they were harder than usual. On a couple of them, I had to out and out give up on my part 2 solutions in favor of those smarter than me.

At any rate, please check out the Github repository, where the Swift 5 solutions to 2019 are now permanently encased:

https://github.com/Wave39/AdventOfCode

Please note that I have removed the year from the repository name, as I intend to keep adding to this one repository all Advents of Code past and present. Currently I am working my way through 2018, so please be patient, as I may have to make code changes on earlier solutions as the Swift versions have moved forward.

BTW, if you are looking for something new and interesting to read in the sci-fi genre, please check out my friend and author Jerry Evanoff. He has self published a book and novella in his Nightmares Through Time series as of the end of 2019, and is planning a larger literary universe to delight and confound. Mostly confound. But it’s a ripping good yarn anywho, so please consider signing up for his newsletter, buying his book, or reading his work through Kindle Unlimited.

Use PowerShell to find all instances of a DLL

Eventually, if you do enough .NET development, you will find yourself in a situation where your application is complaining because it cannot find the right version of a DLL. You could always try to do a search of your hard drive and find these DLLs, but why do it the hard way? Easily enough, you can just use PowerShell to find all instances of a DLL on your computer, which can help you try to track down issues like this.

Here is the PowerShell command that will show you all of the folders, dates, and versions of a DLL that starts with “newtonsoft”. Make sure to substitute in the name of the DLL you are searching for, that you start in the folder that you want to execute the search from (or in other words, if you want to search your entire hard drive, make sure to change directory to the root of your C: drive first), and it can help if you run the PowerShell application as an administrator if you can.

Get-Childitem -Recurse newtonsoft*.dll | Format-Table directory,creationtime,lastwritetime,@{label="ProductVersion";expression={$_.versioninfo.productversion}},@{label="FileVersion";expression={$_.versioninfo.fileversion}}

Or, if you want a listing with fewer columns, try this one:

Get-ChildItem -Recurse newtonsoft*.dll | Format-Table directory,@{label="FileVersion";expression={$_.versioninfo.fileversion}},lastwritetime

BTW, a posthumous Happy Birthday to Dennis Ritchie, a legend in the software development community.

Use ExecuteScalar to insert a database row and return the primary key

I suspect that just about every developer who has had to work with SQL Server has faced this issue. You need to insert a bunch of related records, some of which depend on other records being in the database first. I stumbled on a way to use ExecuteScalar to insert a database row and return the primary key with one call.

To do this, you just add this to the end of your INSERT statement:

SELECT Scope_Identity();

This SQL Server function returns the primary key of the last row that was added to the database with a primary key column. For my instance, I have a SqlText class that encapsulates a lot of the System.Data.Client functionality, so my code looks like this. (I have omitted most of the fields so that this code would be shorter.)

// table 'BillingAddresses' has an integer primary key, auto generated, identity
// 'addressLine1' below refers to a string variable containing line 1 of the address
var sqlString = "insert into BillingAddresses (Line1) values (@Line1); SELECT Scope_Identity();";
var newBillingAddressID = SqlText.ExecuteScalar(sqlString, new { Line1 = addressLine1 });

However, if you are using the standard System.Data.Client namespace, your code would then look like this:

// table 'BillingAddresses' has an integer primary key, auto generated, identity
// 'conn' below refers to an opened instance of a SqlConnection
// 'addressLine1' below refers to a string variable containing line 1 of the address
var sqlString = "insert into BillingAddresses (Line1) values (@Line1); SELECT Scope_Identity();";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Line1", SqlDbType.VarChar);
cmd.Parameters["@Line1"].Value = addressLine1;
var newBillingAddressID = cmd.ExecuteScalar();

Another plug for guidebook.me

I don’t really have anything new to put out there this month, so let me just put in another plug for guidebook.me, the site that I have been developing that lets you track your travel so that you can see where you have been, and plan out where you want to go next.

ASP.NET MVC select tag does not work unless specifically closed

I found out after a bit of pulling my hair out today that if you want to display a dropdown menu via a select tag inside a .cshtml page in your ASP.NET MVC project, you had better close the tag with </select>, because if you rely on the self closing tag (think <select />), then your asp-items will get eaten, along with other miscellaneous things.

Guidebook.me

Please check out my new travel tracking site, Guidebook.me. I have put a lot of time and effort into it, and while it is not done yet, I do have some big plans for it going forward. Let me know if you have any questions or comments.

Organizing a family photo collection using PowerShell, part 2

Just to recap from last month’s post, I have been given the chore of… Organizing a photo collection.

The files were on several computers and backups, so PowerShell on Windows 10 became the main vehicle with which I would try to bring this beast under control.

Plan for organizing a photo collection

  1. Bring photos together from all sources into one place
  2. Remove duplicate photos
  3. Organize photos by month and year

Step 3

Here is the PowerShell script that I used to organize the photos into folders by month and year. (WARNING: Any time you set up any kind of automated file process, make sure that you have backups.)

function fmove($SourceDir,$DestinationDir)
{
	$files = Get-ChildItem $SourceDir
	foreach ($file in $files) 
	{
		$Directory = $DestinationDir + "" + $file.LastWriteTime.Date.ToString('yyyy') + " " + $file.LastWriteTime.Date.ToString('MM')
		if (!(Test-Path $Directory))
		{
			New-Item $directory -type directory -Verbose
		}
		Move-Item $file.fullname $Directory -Verbose
	}
}
 
fmove -SourceDir "C:\Users\Me\Desktop\IntermediateDestination\" -DestinationDir "C:\Users\Me\Desktop\FinalDestination\"

There is not much going on here. The scripts iterates through all files in the source directory. For each individual file, there is a check to see if a folder exists with the last write year and month, creating it if necessary. And finally, the individual file is moved to that folder.

Once this script finishes, you will have a bunch of folders with files in them corresponding (roughly) to their date. However, please keep in mind that this might not be accurate if the files have been processed by other software.

BTW, Happy Birthday to the two dollar bill, issued on this date in 1976 to correspond with Thomas Jefferson’s birthday.