Posts

Showing posts from August, 2021

Git track branch status

If you type git status on a branch and don’t see the relationship to the origin, then you need to set the default upstream: git branch --set-upstream-to origin/MyBranch Thanks to this StackOverflow answer .

Flatten in SQL Server

CREATE TYPE [ dbo ] . [ SingleColumnText ] AS TABLE ( [ TextValue ] NVARCHAR ( MAX ) NULL ) ; create function dbo . Flatten ( @input dbo . SingleColumnText readonly , @delimiter nvarchar ( max ) ) returns nvarchar ( max ) as begin return ( select stuff ( ( select @delimiter + TextValue from @input for xml path ( '' ) , type ) . value ( '(./text())[1]' , 'nvarchar(max)' ) , 1 , 1 , '' ) ) ; end ;

SQL Server Numbers table

if not exists ( select 1 from information_schema . schemata where schema_name = 'util' ) begin exec sp_executesql N 'create schema [util];' ; end ; go create table util . Numbers ( Num int not null , constraint PK_util_Numbers primary key ( Num ) ) ; go declare @MaxValue int = 1000000 ; while ( select count ( 1 ) from util . Numbers ) < @MaxValue begin declare @n int = @MaxValue - ( select count ( 1 ) from util . Numbers ) ; declare @offset int = isnull ( ( select max ( Num ) from util . Numbers ) , 0 ) ; insert util . Numbers select top ( @n ) row_number ( ) over ( order by o1 . [ object_id ] ) + @offset from sys . objects o1 cross join sys . objects o2 end ; select * from util . Numbers order by Num ; go

Median in .NET

dotnet add package MathNet.Numerics https://numerics.mathdotnet.com/ MathNet . Numerics . Statistics . Statistics . Median ( nums )

HTML to text

Install-Package NUglify public static IHtmlContent HtmlToText < T > ( this IHtmlHelper < T > html , string htmlText ) = > new StringHtmlContent ( Uglify . HtmlToText ( $ " <div>{htmlText}</div> " ) . ToString ( ) ) ;

Add view location

 In ASP.NET Core MVC, here’s how to add a new default location to find views: services . AddControllersWithViews ( ) . AddRazorOptions ( options = > options . ViewLocationFormats . Add ( " /Views/SpecialPlace/{0}.cshtml " ) )

Convert UTC to local time in SQL Server

 Thanks to this StackOverflow answer : convert ( datetime , switchoffset ( convert ( datetimeoffset , MyTable . UtcColumn ) , datename ( TzOffset , sysdatetimeoffset ( ) ) ) ) as ColumnInLocalTime

TypeScript settings in csproj

These are the settings I put in the csproj file for TypeScript – it sets values to convert to ES5, takes all TypeScript files and compiles to individual JavaScript files in the /Scripts/js directory. From there, I’ll bundle them into a single site.js file inside of wwwroot/js using BunderMinifier. < PropertyGroup > < TypeScriptTarget > ES5 </ TypeScriptTarget > < TypeScriptJSXEmit > None </ TypeScriptJSXEmit > < TypeScriptModuleKind > CommonJS </ TypeScriptModuleKind > < TypeScriptCompileOnSaveEnabled > True </ TypeScriptCompileOnSaveEnabled > < TypeScriptNoImplicitAny > True </ TypeScriptNoImplicitAny > < TypeScriptNoExplicitAny > False </ TypeScriptNoExplicitAny > < TypeScriptRemoveComments > False </ TypeScriptRemoveComments > < TypeScriptOutFile > </ TypeScriptOutFile > < TypeScriptOutDir > Scripts/js </ TypeScriptOutDir > ...

Add response compression in .NET Core

services . AddResponseCompression ( options = > options . Providers . Add < GzipCompressionProvider > ( ) ) ; app . UseResponseCompression ( ) ;

Force TLS 1.2 with WebClient

In .NET Framework 4.0+, use  this StackOverflow answer to disable TLS 1.0 and force 1.1 or 1.2: ServicePointManager . SecurityProtocol = SecurityProtocolType . Tls11 | SecurityProtocolType . Tls12 ; In prior .NET Framework versions, you can force it without the enum value: public const SslProtocols _Tls12 = ( SslProtocols ) 0x00000C00 ; public const SecurityProtocolType Tls12 = ( SecurityProtocolType ) _Tls12 ; ServicePointManager . SecurityProtocol = Tls12 ;

Catching SQL exceptions in .NET

Here’s one way of handling SQL errors from .NET: For expected errors, like data validation, raise an error with a specific error code and state. Unexpected errors will still blow up with whatever SQL Server’s error message is: create procedure dbo . TestProc ( @customError bit , @sqlError bit ) as begin begin transaction ; begin try if @customError = 1 begin raiserror ( 'This is my custom error.' , 16 , 99 ) ; return ; end ; if @sqlError = 1 begin exec ( 'select * from SomeFakeTable' ) ; return ; end ; select 1 ; commit transaction ; end try begin catch if @@trancount > 0 rollback transaction ; declare @errorMessage nvarchar ( 4000 ) = error_message ( ) ; declare @errorSeverity int = error_severity ( ) ; declare @errorState int = e...

Send To

You can add things to the “Send To” option in Explorer, by simply creating shortcuts to programs in the following directory: % APPDATA % \ Microsoft \ Windows \ SendTo When you put a shortcut here, when you choose this, the file’s full name gets passed as an argument to the program referenced by the shortcut. This can be easier than trying to add something to the “Open With” choices.

God Mode

Windows settings are scattered all over the place. In Windows 10, the Start Menu search function does a pretty good job of finding settings by keyword, but it wasn’t always like this. "God Mode" was built for Windows 7, but still available today. To create a shortcut to "God Mode", which puts all kinds of settings into a single window, create a new folder on your desktop and name it to exactly this: GodMode . { ED7BA470 - 8E54 - 465E - 825C - 99712043E01C } Then just open it and see links to many different settings.

Robocopy

Basic usage of robocopy – there are a lot more options, but this is what I find useful: robocopy c : \ temp \ input \ c : \ temp \ output \ / E / COPY : DAT / DCOPY : DAT / XF excl1 . * / XF excl2 . * / XD excl * / MIR /E will include subdirectories /COPY uses DAT by default (Data, Attributes, Timestamps) /DCOPY uses DA by default /MIR will delete items that are in the target but not the source

Shell commands

Thanks to Shawn Brink for publishing the complete list on https://www.tenforums.com/tutorials/3109-shell-commands-list-windows-10-a.html Here is a subset of that list of items that I use on a regular basis: shell:AppsFolder Applications shell:desktop Desktop shell:downloads %UserProfile%\Downloads shell:Programs %AppData%\Microsoft\Windows\Start Menu\Programs shell:Quick Launch %AppData%\Microsoft\Internet Explorer\Quick Launch shell:SendTo %AppData%\Microsoft\Windows\SendTo shell:Start Menu %AppData%\Microsoft\Windows\Start Menu shell:StartMenuAllPrograms StartMenuAllPrograms shell:Startup %AppData%\Microsoft\Windows\Start Menu\Programs\Startup

Convert MP4 to MP3

Using FFmpeg for Audacity command line tool, here’s a simple batch file that lets you drag a series of MP4 files on top of the batch file, and it will convert them all to MP3. @ echo off :start if [ %1 ] = = [ ] goto done set args = %1 "c:\Program Files (x86)\FFmpeg for Audacity\ffmpeg.exe" - i %args% %args%.mp3 shift goto start :done pause

Convert PDF to JPG

This is a pretty limited use case, probably something that will never be needed, but if you need to convert a PDF file to a JPG image, you may be able to do it with this command: convert .exe - verbose - density 125 c : \ temp \ myfile.pdf - quality 100 c : \ temp \ myfile.jpg Prerequisites ImageMagick Ghostscript VC++ 2013 redistributable

Create Bootable USB from Windows

I've had amazingly bad luck with different programs and operating systems, just trying to create bootable thumb drives. In Windows, when creating a Windows bootable USB, this seems to work, with the instructions found here : No promises that this will work everywhere. C:\> diskpart Diskpart> list disk Diskpart> sel disk 1  <-- (the number of your usb) Diskpart> clean Diskpart> create part pri Diskpart> format fs=ntfs quick Diskpart> Active Diskpart> Assign Now copy the install files to the drive, and use it to boot.

Reload page in javascript

To reload a page without re-posting, you may have seen something like: location . href = " " + location . href ; This doesn’t work if there’s a hash in the URL. Instead, do this: location = location . href . split ( " # " ) [ 0 ] ;

ASP.NET end response without ThreadAbortException

Thanks to this answer on StackOverflow for this answer: // Sends all currently buffered output to the client. HttpContext . Current . Response . Flush ( ) ; // Gets or sets a value indicating whether to send HTTP content to the client. HttpContext . Current . Response . SuppressContent = true ; // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event. HttpContext . Current . ApplicationInstance . CompleteRequest ( ) ;

Rolling text file to GZip Trace Listener

public class CustomTraceListener : TraceListener { private readonly string _fullFileName ; private readonly int _maxFileSize ; private FileStream _fileStream ; private int _numBytes ; private string _currentLogFileFullName ; public CustomTraceListener ( string fullFileName , int maxFileSize = 10 * 1024 * 1024 ) { var fileInfo = new FileInfo ( fullFileName ) ; if ( ! fileInfo . Directory . Exists ) { throw new ApplicationException ( " Invalid directory for trace file " ) ; } _fullFileName = fullFileName ; _maxFileSize = maxFileSize ; InitializeFile ( ) ; } private void InitializeFile ( ) { if ( _fileStream ! = null ) { _fileStream . Dispose ( ) ; _fileStream = null ; using ( var inputStream = File . OpenRead ( _currentLogFileFullName ) ) ...

SQL Dates Table

create table dbo . Dates ( TheDate date not null , constraint PK_Dates primary key ( TheDate ) ) ; go declare @StartDate date = '1950-01-01' ; declare @EndDate date = '2099-12-31' ; ; with cte as ( select @StartDate [ TheDate ] union all select dateadd ( day , 1 , [ TheDate ] ) from cte where dateadd ( day , 1 , [ TheDate ] ) < = @EndDate ) insert dbo . Dates ( TheDate ) select TheDate from cte option ( maxrecursion 0 ) ; go select * from dbo . Dates order by TheDate ; go

Read query string with URI.js

// <script src=" https://bowercdn.net/c/urijs-1.18.10/src/URI.min.js "></script> // Page is: http://example.com/index.html?a=1&b=2 var parsedURI = URI . parse ( document . location . href ) ; // { query: "a=1&b2=", protocol: "http", hostname: "example.com", ... } var query = parsedURI . query ; // a=1&b=2 var parsedQuery = URI . parseQuery ( query ) ; // { a: "1", b: "2" } var a = parsedQuery . a ; // "1" // In a single line: a = URI . parseQuery ( URI . parse ( document . location . href ) . query ) . a ; // "1"

NodeJS Prompt

Sometimes you just need a simple terminal application that requests user input. Here’s a quick way to prompt the user for input: const readline = require ( " readline " ) ; const rl = readline . createInterface ( process . stdin , process . stdout ) ; rl . on ( " line " , line = > { console . log ( ` You typed ${ line } ` ) ; rl . prompt ( ) ; } ) ; rl . setPrompt ( " Action> " ) ; rl . prompt ( ) ;

NPM Package Location

Global libraries You can run npm list -g to see where global libraries are installed. On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node. Windows XP: %USERPROFILE%\Application Data\npm\node_modules Windows 7: %AppData%\npm\node_modules Non-global libraries Non-global libraries are installed the node_modules sub folder in the folder you are currently in. You can run npm list to see the installed non-global libraries for your current location. Reference Answer copied from this Stackoverflow question

Mailgun in Javascript

Mailgun is a great email service with reasonable pricing, including a fantastic free tier. Once you set up the account, sending email from NodeJS is incredibly easy. var api_key = ' MY_API_KEY ' ; var domain = ' mg.MYDOMAIN.com ' ; var mailgun = require ( ' mailgun-js ' ) ( { apiKey : api_key , domain : domain } ) ; var data = { from : ' Some User <SOMEUSER@MYDOMAIN.com> ' , to : ' person1@example.com,person2@example.com ' , subject : ' Hello ' , text : ' This is a test! ' , html : ' This is a <b>test</b>! ' } ; mailgun . messages ( ) . send ( data , function ( error , body ) { console . log ( body ) ; } ) ;

Simple Bootbox message with callback

bootbox.js is a nice simple replacement for alerts. Here’s a quick extension that shows a message by hiding any existing boxes, then showing the new one. Since it’s using Bootstrap’s event-based modals, you have to wait for one to finish loading before closing it or expecting it to be open. function showMessage ( title , body , callback , noButton ) { bootbox . hideAll ( ) ; var data = { title : title , message : body } ; if ( callback ) { data . onShown = callback ; } if ( noButton ) { bootbox . dialog ( data ) ; } else { bootbox . alert ( data ) ; } } showMessage ( " Loading " , " Working... " , function ( ) { // Do something showMessage ( " Second Message " , " This is the real message " ) ; } , true ) ;

SQL Merge Insert/Update with output

if object_id ( 'tempdb..#joe' ) is not null drop table # joe ; go declare @results table ( id int ) ; create table # joe ( id int not null identity , name varchar ( 100 ) ) ; insert # joe select 'John' [ name ] union select 'Jane' union select 'Mary' union select 'Pat' ; select * from # joe order by id ; declare @id int , @name varchar ( 100 ) ; -- Update --set @id = 2; set @name = 'Phil'; -- Insert --set @id = null; set @name = 'Phil'; merge # joe tgt using ( select @id [ id ] ) src on tgt . id = src . id when matched then update set name = @name when not matched then insert ( name ) values ( @name ) output inserted . id into @results ; select * from # joe order by id ; select * from @results ;

Claims Authorization Example

Startup.cs using System . IO ; using System . Linq ; using System . Security . Claims ; using Microsoft . AspNetCore . Authentication . Cookies ; using Microsoft . AspNetCore . Builder ; using Microsoft . AspNetCore . DataProtection ; using Microsoft . AspNetCore . Hosting ; using Microsoft . Extensions . Configuration ; using Microsoft . Extensions . DependencyInjection ; using Microsoft . Extensions . Hosting ; using Newtonsoft . Json ; namespace WebApplication25 { public class Startup { public Startup ( IConfiguration configuration ) { Configuration = configuration ; } public IConfiguration Configuration { get ; } public void ConfigureServices ( IServiceCollection services ) { var cookieAuthSection = Configuration . GetSection ( " CookieAuth " ) ; string appName = cookieAuthSection . GetValue < string > ( " Application...