Posts

Showing posts from April, 2021

SQLite In-Memory Database

Image
SQLite has an option for running completely in-memory, rather than using a local file on disk. This may be perfect for doing one-time data manipulation or other short-term tasks. Just use :memory: instead of the database filename, and you'll get the in-memory database. Or use an empty string, to use memory only, but a temporary file on disk if memory starts to run low. View code on GitHub

JavaScript splice, slice, shift, pop

Image
These four functions are commonly used to copy or modify arrays in JavaScript. I generally have the signatures printed as a cheat sheet since I can never keep them all straight. splice slice shift pop View code on GitHub

Modify web.config appsettings value

var config = WebConfigurationManager . OpenWebConfiguration ( " ~ " ) ; var section = ( AppSettingsSection ) config . GetSection ( " appSettings " ) ; section . Settings [ " something " ] . Value = " newValue " ; config . Save ( ) ;

NodeJS read/write text files

" use strict " ; ( function ( ) { var fs = require ( " fs " ) ; var readline = require ( " readline " ) ; fs . readFile ( " input.json " , function ( error , data ) { var obj = JSON . parse ( data ) ; fs . writeFile ( " output.json " , JSON . stringify ( obj ) , function ( err ) { if ( err ) { console . log ( " Error: " + err ) ; } else { console . log ( " Saved " ) ; } } ) ; } ) ; ( function ( ) { var outputStream = fs . createWriteStream ( " output.txt " ) ; var lineReader = readline . createInterface ( { input : fs . createReadStream ( " input.txt " ) } ) ; lineReader . on ( " line " , function ( line ) { console . log ( " Line: " + l

NodeJS Read/Write Files

const fs = require ( " fs " ) ; const readline = require ( " readline " ) ; // Read full file fs . readFile ( " myfile.txt " , { encoding : " utf-8 " } , ( err , data ) = > { console . log ( " Full file contents: " ) ; console . log ( data ) ; console . log ( " =================== " ) ; } ) ; // Read file line-by-line var lineReader = readline . createInterface ( { input : fs . createReadStream ( " myfile.txt " ) } ) ; lineReader . on ( " line " , line = > { console . log ( ` Line: ${ line } ` ) ; } ) ; lineReader . on ( " close " , ( ) = > console . log ( " DONE " ) ) ; // Write full file fs . writeFile ( " myfile.txt " , " some file contents " , err = > { if ( err ) console . error ( err ) ; } ) ; // Write file line-by-line var outputStream = fs . createWriteStream ( " myfil

Simple SQL Server backup/restore

-- Back Up --------------------------------------------- declare @filename nvarchar ( 255 ) = 'C:\backups\' + format ( sysutcdatetime ( ) , 'yyyyMMddHHmmss' ) + '.bak' ; backup database MyDB to disk = @filename ; go -- Restore --------------------------------------------- -- Find the logical names - result will be the MDF and LDF -- logical names: restore filelistonly from disk = 'C:\backups\20201103130743.bak' ; go restore database DifferentDB from disk = 'C:\backups\20201103130743.bak' with replace , move '**MDF Logical Name**' to 'c:\data\DifferentDB.mdf' , move '**LDF Logical Name**' to 'c:\data\DifferentDB_log.ldf' ; go

Make database readonly

Pretty straightforward to set a database to readonly mode. If the database is currently in use, it may get complicated, but as long as it's currently unused, this should work: -- Set to readonly: use master ; go alter database mydatabase set read_only with no_wait ; go -- Re-enable writing: use master ; go alter database mydatabase set read_write with no_wait ; go

Check if two images are similar

I was trying to dedupe my photos, and found that identical photos didn't have identical file contents, because of the way they were stored in Google Photos, or iCloud, or Amazon Photos, or wherever else I had them stored. So this method will look at two photos, see if they have the same dimensions, then check to see if they are similar photos. It reduces both photos to 16x16 (regardless of original dimensions), then compares the RGB values of each pixel. If the photos are different enough, that number will be high. If the difference is close to zero, then they are likely the same photo, or at least very similar. I wouldn't use this if you aren't willing to accept a false positive once in awhile - maybe back up your photos to stupidly cheap cloud storage (AWS and Azure have 1$/TB/month now) before using this to dedupe. static bool AreSimilar ( string file1 , string file2 ) { Console . WriteLine ( " Comparing:\r\n {0}\r\n {1} " , file1 , file2 ) ; us

SQL Print output in ADO.NET

Thank you to this StackOverflow answer for showing how to retrieve PRINT result from SQL Server in C#: conn . InfoMessage + = ( sender , e ) = > { // e.Message contains the print output } ;

Javascript rest parameters

// collects parameters and turns them into an array // must be the last parameter // no IE support // no Safari support function writeArguments ( name , . . . values ) { console . log ( ` my name is ${ name } ` ) ; console . log ( JSON . stringify ( values ) ) ; // [1,2,3] } writeArguments ( " john doe " , 1 , 2 , 3 ) ;

Javascript arguments vs named parameters

// different behavior in ES5 non-strict vs ES5 strict and ES6 function go ( id , name = " jack " ) { ++ id ; name = " bill " ; // the values of the variables (2, "bill") console . log ( id ) ; console . log ( name ) ; // the actual values passed in (1, "john") // but in ES5 non-strict, they are linked to the named ones, so (2, "jack") console . log ( arguments [ 0 ] ) ; console . log ( arguments [ 1 ] ) ; } go ( 1 , " john " ) ;

.NET Random Numbers

Image
.NET gives you two ways to generate random numbers - a fast but insecure way, and a cryptographically pseudorandom way which is safe to use for cryptography. Both are easy to use. For non-secure purposes, create a single instance of Random - this can be a singleton or a static field - just don't create a new one every time you need it, because you might end up with dupes that way. Random is also not thread-safe, so make sure you access it in a thread-safe way if there's the possibility of multiple threads accessing it. View code on GitHub

TypeScript/JavaScript import statements

Image
In TypeScript, and in JavaScript if you're using modules, you can import code from other places using the import statement. This lets you bring in code from elsewhere in your project, or third party libraries from places like deno.land or NPM. View code on GitHub

Target Typed New Expressions

Image
Back in the old days, declaring variables and instantiating objects made for some pretty lengthy and ugly code: Dictionary < int , string > dictionary = new Dictionary < int , string > ( ) ; Then came "var", which let you declare a variable and it would be strongly typed to be whatever the right side of the equals sign says it is. This made things much better: var result = new List < string > ( ) ; // result is of type List<string> In scenarios where you needed your variable to be of a base class or interface type, you'd still do things the old fashioned way, but for a lot of simple code, var was a game changer. However, var is occasionally abused, where it's not obvious what the right-side type is - in those scenarios, I prefer opting for skipping var. var something = GetSomething ( ) ; // What type is this variable? Don't know unless you follow it in the IDE. Something something = GetSomething ( ) ; // Better

SQLite AutoIncrement

Image
One of the interesting things in SQLite is the ROWID column, which is a special column created on all tables (with some exceptions) by default. This can be an alias for a defined column, as long as that columns is an INTEGER primary key column, or it can act as the primary key by itself. But the ROWID behaves differently from SQL Server IDENTITY columns or Oracle sequences, because they can be reused - if you delete the record with the highest ROWID and then insert a new one, you'll get a repeat. If you're not using this value for any particular purpose, this might be just fine. But if you want a new ID with every new record, then use the AUTOINCREMENT indicator on the column when creating the table. View code on GitHub

SQLite in .NET

Image
SQLite is a great database when you don't need the benefit of a full server-based database. You can use it in desktop or mobile applications, for small or medium sized web applications, or anywhere else you can think of. It's simple, but still has a rich feature set. Some of its behavior is a little bit quirky , but once you learn how to use it, you can use it in your application basically the same way as you would SQL Server or any other database. This video will walk through some of the basics, showing how similar it is to any other database when using .NET. View code on GitHub

DateTimeOffset

Image
.NET's DateTime struct is basically just a number with some properties and methods wrapped around it. It can represent a date and time, but no concept of where in the world that time is. The DateTimeOffset struct adds on a UTC offset, which means it now represents a given point in time (ignoring leap seconds - that screws things up). Suppose you have a DateTime of "2021-04-09 12:34:56.789". This is precise to the millisecond, but is that UTC time? Arizona time? Does it account for daylight saving time? Who knows? A DateTimeOffset includes the UTC offset, so "2021-04-09 12:34:56.789-0700" is much clearer - this is 7 hours before UTC time. You can decide what you want to do with it from there. Note that this is an offset, not a time zone - this doesn't account for daylight saving time or other weird scenarios. However, in my personal experience, unless you're strictly 100% local with no possibility of change, I would treat all times everywhere as

Non-buffered Output in ASP.NET

Most of the time, it makes sense to build a complete response and return it all at once. Sometimes, if you have a big result, like a large report, you’ll want to send the file a response a little at a time, to keep from storing a huge item in memory. You can write to a file and then output that file in the response, or you can dynamically write and flush the response a little at a time, until the response completes. public ActionResult GetFile ( ) { string [ ] lines = { " line 1 " , " line 2 " , " line 3 " , " line 4 " } ; Response . Clear ( ) ; Response . ClearHeaders ( ) ; Response . ContentType = " text/plain " ; Response . AddHeader ( " Content-disposition " , " attachment;filename=somefile.txt " ) ; Response . Buffer = Response . BufferOutput = false ; foreach ( string line in lines ) { Response . Write ( line + " \r\n " ) ; Re

Which version of .NET Core is installed

Image
Turns out there’s a super easy command for seeing which version of .NET Core is installed on your desktop or server:  dotnet --info

Versioned content in MVC

When you add a script or stylesheet to your HTML page, those requests can be cached by the browser, potentially providing outdated content to the browser. If you’re not using a bundler or anything fancy like that, then the only way to prevent this problem is to create a brand new URL whenever your script file or stylesheet changes. This is easily accomplished with a querystring, so if your app was previously using app.js?v=1 and you change that to app.js?v=2, the browser will definitely not use the cached version, and will instead make a new request to the server, and pull the latest one. Using the following technique, you can guarantee that you’ll always pull the latest script and stylesheet when working in dev, and when in production, you can define a “version key”, possibly in a config file or database, and if you ever update just the static content, you would only need to update that key, and it would force all browsers to pull new content. public static class HtmlExtensions {

JSON infinite loops in ASP.NET

If you accidentally (or purposely) have an infinite loop in an object, where it has a reference that points back to itself, when you try to return that object as JSON in ASP.NET, you get an error: JsonSerializationException: Self referencing loop detected for property... To avoid that, you can add a line to your Startup ConfigureServices method: // dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson services . AddNewtonsoftJson ( options = > { options . SerializerSettings . ReferenceLoopHandling = ReferenceLoopHandling . Ignore ; } ) ;

sp_executesql

Image
SQL Server lets you execute dynamic SQL with the EXEC command. However, if you're accepting any user input as part of the query, you'll be subject to SQL injection attacks. The system proc sp_executesql gives you the ability to build a parameterized statement dynamically, and execute it, passing in the parameter values. As long as you're building the query safely, you won't be subject to SQL injection. View code on GitHub

Switch Expressions

Image
The switch statement in C# has been there since the beginning. Originally it was for a simple data type only, and you could only go through cases of constant values. Now there's so much more. View code on GitHub

ASP.NET JSON Self Referencing Properties

Image
In object-oriented languages, an object can hold a reference to itself in a property, and there's no problem with that. However, when you go to serialize that object, you run into issues. An object with a self-referencing property that loops back to itself would cause an infinite loop and crash when trying to serialize it. Here's how to avoid the error in ASP.NET. I'd recommend against the idea in the first place, opting instead for simple data types, but this is here if you need it. View code on GitHub