ListShortcuts.csx

#r "Interop.IWshRuntimeLibrary.dll"
//generated by referencing "Windows Script Host Object Model" in Visual Studio project


//from here: http://stackoverflow.com/a/4909475/813599
using IWshRuntimeLibrary;
using System.Text.RegularExpressions;

var wsh = new WshShell();

var shortcutFileNames = System.IO.Directory.EnumerateFiles(Env.ScriptArgs[0], "*.lnk");
var wshShortcuts = new Dictionary<String, IWshShortcut>();
foreach (var shortcutFileName in shortcutFileNames)
  wshShortcuts[Regex.Match(shortcutFileName, ".*?- (.*?).lnk").Groups[1].Value] = (IWshShortcut)wsh.CreateShortcut(shortcutFileName);

//var maxFileNameLength = wshShortcuts.Max(kv=>kv.Key.Length);

Console.WriteLine("Display Name | Target | Arguments");
Console.WriteLine("--- | --- | ---");
foreach(var sc in wshShortcuts)
  Console.WriteLine($"{sc.Key} | {sc.Value.TargetPath} | {sc.Value.Arguments}");

sample output

image

Launch .CSX as conveniently as .BAT files

first, get Chocolatety if you don’t already have… killer handy

@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

then make sure you have a .csx runner… either ScriptCS or csi.exe starting with Visual Studio 2015 update 3

choco install ScriptCS

setup the .csx to runner file association

assoc .csx=CSharpScript
ftype csharpscript=C:\ProgramData\chocolatey\bin\scriptcs.exe %1 -- %~2

%~2 means all args starting with #2… see ftype docs for more

FYI for TCC LE folks, apparently i’ve stumbled into a rare backwards compatibility gap… TCC LE doesn’t seem to support the %~2 syntax like cmd.exe and it escapes “%” differently, so substitute that portion of the ftype line above with “%%1 — %%2 %%3 %%4”

lastly, edit your PATHEXT system environment variable to include .CSX which allows us to leave off the extension to launch our scripts just like native commands! =)

setx PATHEXT %PATHEXT%;.CSX /M
refreshenv.cmd

TCC LE requires OPTION > Startup > PathExt for the above to work

refreshenv comes from Chocolately… it refreshes the current command line environment from registry, which we just updated via setx

or runas admin > C:\Windows\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables
image

with all that fun stuff in place, we can finally do something nifty like this:

C:\> myCSXScript arg1 arg2

beautiful! =)

see my other CSX examples

Using “C# Interactive” aka CSI/CSX for ETL

motivation

interactive C# offers typical REPL benefits ala powershell without the mental context switch required to leave our beloved C# syntax =)
 

notable

  • great MSDN reference article
  • CSX syntax can be executed from either Visual Studio 2015 (as of update 1) > View > Other Windows > C# Interactive
  • -or- C:\Program Files (x86)\MSBuild\14.0\bin\csi.exe
    • then #load file.csx

Extract

this example is based on a low fidelity web page as the raw data source
… it’s really nice to have all the convenient one liner RESTy methods of System.Net.WebClient available now vs the lower level WebRequest/WebResponse pattern that came with .Net 1.0. E.g. client.DownloadString, DownloadFile, etc.

Transform

trivially demonstrative in this case, simply a string.Split call 🙂

Load

demonstrates leveraging SQL Server’s Table-Valued-Parameter functionality to bulk upload rows which are then conveniently manifested inside the receiving stored procedure as a standard sql rowset, ready for tpyical DML like joining to other tables, etc.
 

SQL definition

CREATE TYPE dbo.SpreaderData_UDT AS TABLE
(
    [SpreaderDataID] [INT] PRIMARY KEY,
    [SpreaderID] [INT],
    [Speed] [INT],
    [Density] [INT],
    [SpreadQty] [INT],
    [Setting] [VARCHAR](100)
)
GO

-- crucial - SQL Server yields a unintuitive error message when this has not been done
GRANT EXECUTE ON TYPE::dbo.SpreaderData_UDT TO PUBLIC
GO

CREATE PROCEDURE [dbo].SpreaderData_Table_u
@SpreaderData dbo.SpreaderData_UDT READONLY -- <= ***** crucial
AS BEGIN

UPDATE sd SET
  sd.Setting = sd2.Setting
FROM dbo.SpreaderData sd
JOIN @SpreaderData sd2 ON sd2.SpreaderDataID = sd.SpreaderDataID

END
GO

scrape.csx

Bash script – loop over inline list of files

#!/bin/bash

#echo $BASH_VERSION

# read args:
# -r = disable backslash escaping
# -d '' = read the whole here-doc as one big input vs stopping stopping at the first new line as the default delimiter
# -a = put the results into an array
#the minus in "<<-" provides for indenting the here-doc lines, but with TABS ONLY
#bash4 is way easier but wanted to be portable: readarray -t arr <<-"EOT"
IFS=$'n' read -r -d '' -a arr <<-'EOF'
    /file/path/1
    /file/path/2
    /file/path/3
EOF

#echo ${#arr[*]}

# http://stackoverflow.com/questions/9084257/bash-array-with-spaces-in-elements
# disable default space delimiter
IFS=""
for filePath in ${arr[*]}
do
  stat "${filePath}"
done

unset IFS

[SOLVED] Acer Aspire One won’t boot Syslinux USB thumbdrive

Looks like my particular issue was the default partition size on my 16GB thumbdrive. Once I formatted the USB with a 2GB partition and installed Syslinux to that, it booted up right away where previously it would hang on the first “Syslinux Copyright Peter Anvin” message. More details:

  • Acer Aspire One model#: 722-C62bb (looks like this is an 11” model)
  • Always handy to have another computer to work from (for web searching, trial and error formats on the USB drive, etc) when trying to fiddle with boot issues on another… my other computer is a Win8 desktop.
  • Syslinux actually came into my picture because I was looking to create Comodo’s Rescue Disk. Comodo (v6.2) has a convenient point and click process to push their linux based rescue disk to a USB.
  • I used diskpart (on my Win8 box) to create the smaller partition… here’s the core commands:
    • list vol (to get a feel for your windows drive letters and not format the wrong one 🙂
    • list disk (same for raw physical disks)
    • select disk X (MAKE SURE YOU CHOOSE THE RIGHT ONE!!)
    • (MAKE SURE AGAIN)
    • clean (THIS WIPES THE DISK!!!)
    • create part primary size=2048 (2GB worked for me in this context)
    • active
    • format fs=fat label=”COMODO” quick (I chose old school FAT filesystem looking for most downlevel compatibility, not sure if it was actually necessary vs FAT32. NTFS is notably the least compatible option for linux booting. Quick means do a quick format.)
  • Then I just let Comodo do it’s thing and that result booted up right away for me – yay 🙂

SED – Insert text after match

General syntax:

  • sed “s/search-for-regex/& replace-with/” filename.txt

Example:

  • sed “s/BEGIN AS/& nnSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED/” Plans_s.sql

Explanation:

  • s/search-for-regex/replace-with/ = search and replace command
  • & = the matched text (effectively leaves the matched text alone rather than “replacing” it)
  • n = carriage return

SQL Split AWK Script

Split the output from SQL Server Management Studio (SSMS) > View > Object Explorer Details > “Script {function|view|procedure} as” into individual files
Note: The current RegEx’s are tailored around the following scripting options (see comments to change):

  • “Include descriptive headers” = true  (this is the default after SSMS 2008 install) – located under:  SSMS > Tools > Options > SQL Server Object Explorer > Scripting > General scripting options)
  • “Schema qualify object names” =  false (NOT the default) – under: … > Object scripting options

Download GAWK.exe for Windows: link1, link2

# example: gawk -f sqlsplit.awk file-to-split.sql

BEGIN {
  outfile = "erase_me.sql" #start off with a dummy file to get the ball rolling
  IGNORECASE = 1
}

END {
  #close off last file
  print "grant "grant" on "arr[1]" to publicngon" >>outfile
  close(outfile)
}

//***** Object:/ {
  #upon matcing the "object" comment, close off the previous output file
  print "grant "grant" on "arr[1]" to publicngon" >>outfile
  close(outfile)

  #start up the new one
  match($0, /[(.*)]/, arr) #change to something like /[dbo].[(.*)]/ if you want “Schema qualify object names” enabled
  outfile = arr[1]".sql"
  print "--$Author:$n--$Date:$n--$Modtime:$n--$History:$n" > outfile
}

/^(create) +(proc|function|view)/ {

  grant = "execute"
  if ($2 == "view") grant = "select"

  printf "if not exists(select 1 from sysobjects where name = '"arr[1]"')ntexec('create "$2" "arr[1] >>outfile

  # function is a little trickier because it could be a table or scalar return type requiring slightly different create function signature
  if ($2 == "function") {
 
    lines = ""
    while((getline line) >0) {
      lines = lines line"n"
      match(line, /returns/, a)
      if (a[0] != "returns") { continue }

      #debug: printf "line = %s, a[0] = %s, a[1] = %s, a[2] = %s, a[3] = %sn", line, a[0], a[1], a[2], a[3]

      match(line, /table/, a)
      if (a[0] == "table") {
        grant = "select"
        print "() returns table as return select 1 as one')" >>outfile }
      else print "() returns int begin return 0 end')" >>outfile
      break

    }
  }

  #proc/view
  else {
    print " as select 1 as one')" >>outfile
  }

  print "GO" >>outfile

  sub(/create/, "alter") #change the create to alter
  sub(/$/, lines) #tack back on the lines "eaten" to figure out whether function was tabular or scalar
}


{ 
  print  >>outfile
}

SymLinks (and their ilk) Are Excellent System Restore ‘Glue’

Ok i know this is 20+ years late for anybody that’s enjoyed any of the sweet but non mainstreamy flavors of  ‘nix… but now that Vista (blech!!) and Windows 7’s version of NTFS supports SymLinks (aka Soft) & HardLinks so well we can enjoy ourselves just as much over in Mr. Bill’s backyard (or I guess it’s Mr. Ozzie’s backyard now aint it) Go get this puppy: Link Shell Extension Nevermind that his version history starts at 1999 😐 We can rest easy that Vista was the first to do an actual Symbolic Link (i.e. softies)… but yeah we’ve been missing out, hardies have been in there since NT4… so we could’ve been having some fun… the biggest downside ‘til now in my naive opinion: the hard flavor couldn’t cross drive letters… yes, just another annoying distraction that could be mitigated in other ways, but now we don’t have to think about it (even less). My main point here is… i re-re-re-re-re-load Winders at the drop of a hat (i’m kinda neurotic about it… i recommend this behavior… what was that?! don’t listen to the voices?) anyway, i’ know i’m not the only one that has rallied the wagons behind saving all their precious files under one root folder and then carries that carpet bag from one system reload to another.  Well SymLinks are here to help.  Listen up soldier, here’s the straight doo doo: Rather than actually leaving your numerous tweaked files sitting hither and thither at "%appdata%MicrosoftInternet ExplorerQuick Launch” and “c:usersbeejfavorites” and “c:windowssystem32driversetchosts” and and and… leave them all in a nice tidy centralized folder structure of your own design and then SymLink the schnikees out of them. This shell extension lets you drag and drop to create magical “short cuts” that actually act like the real file but aren’t really there. You catchin me? No?  Just load the dang thing, right mouse, drag, drop, look for the “Drop Here” menu and throw a dart at your options… there’s various ups and downs to each of the Link flavors… e.g. I noticed that soft links wouldn’t allow navigation from a shared folder entrance… who knew? Enjoy!  I’m having a blast with them… all over the place.  Can’t wait to re-load again! Update 09 Oct 2009:  SymLinks are also coming in super handy as a way of centralizing and sharing common source code files (I have a feeling this is something graybeard coders have been doing for years but that you just don’t hear about it much)… I SymLink a “copy” of the common source file into each project folder tree where I want to reuse… obviously this is way easier to manage than keeping track of updating actual copies in every folder… it also helps keep me more honest about sticking to the “code contract” that I originally intended… if I’ve hacked something up for one project, then compiles will bomb and remind me… it forces me to keep things generic and therefore promotes more reusable code.

Transparent Command Shell (Windows)

Nice, someone’s gone and created the perfect pill for even the most serious case of Mac OS X Terminal envy…

I give you: Console2 !

It’s got dang near everything I could ever want to configure… somebody really loves their command shells mmm hmmm 😛
Only little nit pick I can come up with is that I think the Mac actually allows you to set the transparency of the just the background… so that the text and the outer frame still look crisp and solid.