Sql Connection String for .NET


Standard Security:

"Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"


References:

(on unit vs. integration tests) So maybe this is the distinction I find useful. There are tests where a failure points directly to the problem.
These tests are tests either of well-understood abstractions or using only well-understood abstractions.
Then there are tests where a failure indicates a genuine problem, but where oh where? - Kent Beck

Patterns Simpl: Dependency Injection

"In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it."

A better quote for the initiated to DI/IoC would be:

"Dependency Injection was originally called Inversion of Control (IoC) because the normal control sequence would be the object finds the objects it depends on by itself and then calls them. Here, this is reversed: The dependencies are handed to the object when it's created. This also illustrates the Hollywood Principle at work: Don't call around for your dependencies, we'll give them to you when we need you." -javaworld.com

In .NET, .resx resource files that contain different inputs based on the culture settings of the client is an example of DI.

Another simple and clear example of Dependency Injection in action is in ASP.NET Core Authentication.

The built-in Authentication Controller and the Startup.cs Configure() method are designed to work with an interface and not one specific/concrete class of authentication provider. It uses IAuthenticationSchemeProvider which provides a generic and flexible structure that leaves the specific type of authentication up to the developer(s) (Google, Microsoft, Twitter, GitHub, Instagram, Facebook, etc.).

These different authentication types/providers are what the IAuthenticationSchemeProvider depends on to handle the authentication process for ASP.NET Core applications.

The developer injects the dependency(s) of his or her choice.

A common form of Dependency Injection is Localization of display text in applications

Loose coupling is key for interoperability with other apps and services, if your dependencies are more generic, your system is more extensible

Find all instances of a string within a string in T-SQL

CREATE FUNCTION dbo.FindPatternLocation
(
    @string NVARCHAR(MAX),
    @term   NVARCHAR(255)
)
RETURNS TABLE
AS
    RETURN 
    (
      SELECT pos = Number - LEN(@term) 
      FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@string, Number, 
      CHARINDEX(@term, @string + @term, Number) - Number)))
      FROM (SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
      FROM sys.all_objects) AS n(Number)
      WHERE Number > 1 AND Number <= CONVERT(INT, LEN(@string)+1)
      AND SUBSTRING(@term + @string, Number, LEN(@term)) = @term
    ) AS y);
Simply use the function above.

If you want to understand technically how this works, see the reference below.

Essentially, this function dynamically creates a table (CTE) of the term being searched for with Number being the Row_Number of each charindex within the string.

This CTE is then searched to elicit the starting positions of each location where string term matches ([WHERE] SUBSTRING(@term + @string, Number, LEN(@term)) = @term).

Usage:




The part: "SELECT ROW_NUMBER() OVER (ORDER BY [object_id].." is there to provide space to establish the CTE with which to store search string indexes. If you need more space to traverse over (your search string is > 2k characters) you can use sys.all_columns instead of sys.all_objects or a CROSS JOIN for tables with greater than 8k records.


Reference: https://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1

All credits: Aaron Bertrand. He is a T-SQL genius. If it can be done in T-SQL, Aaron has done it, benchmarked it and probably blogged about it: https://sqlperformance.com/author/abertrand

Visual Studio Config Transforms

When you are working on software that needs to target different resources for different environments (ie. local, DEV, STAGE, PRODUCTION), you can easily manage your VS project environment through the use of .config transformation files.

Here is your default web.config:



Simply make an alternate version (with the same name) of the element you wish to change in your various configuration transformations (web.DEBUG.config, web.Development.config, etc.). In this example, we are setting up a transform to change the connection string that has the name, "applicationConnStr":



NOTE: The same configuration element (the same name, specifically) you want to transform must be in the base web.config file.

By default, the transformation we have set up will only be applied when the project is published. In order to get the transformations working with each build, you must edit the bottom of the *.csproj file with the following Target:

  <Target Name="BeforeBuild">
    <TransformXml 
        Source="Web.Base.config" 
        Transform="Web.$(Configuration).config" 
        Destination="Web.config" />
  </Target>



And be sure to uncomment the code, it is commented out by default. Now select a different build configuration, build your project, and you should see the "applicationConnStr" transformed to match the element from the web.config.[Debug||Release||etc.] that you selected to Build:




To add new web.config transform files, just right click on the web.config file and select "Add Config Transformation".



To associate your transformations with different builds, under the Build Dropdown, select "Configuration Manager..." and configure as you like:




Setting up build configurations that point to different web.configs (actually web.config "transforms") allows you to debug and run code according to your needs (ie. show DEMO at a meeting, Debug Development to uncover a bug, point to local for ongoing development, etc.).

ASP.NET Core has a very different configuration setup that uses JSON objects and more configurable things in .NET Core Startup.cs; this reference is for .NET Standard.

The key in all of this is the name of the element you are matching and then replacing. It just has to match in both places and all will be transformed on your application's web.config. In this example, we matched and replaced the value for a config element with the name, "applicationConnStr".

In a real-world scenario, there are many things that we could dynamically replace through config transforms: database connection strings, image servers, mail servers, file shares, printer locations, encryption keys, etc.).

Reference: https://docs.microsoft.com/en-us/aspnet/web-forms/overview/deployment/visual-studio-web-deployment/web-config-transformations

Customize SSRS Stylesheet

This is an easy thing to do, especially if you are well-versed in CSS/DOM designing.

1). Go to this location and open up HtmlViewer.css in your favorite text editor:




2). Edit/override styles however you see fit. You can change almost all of the styles on the SSRS toolbar:

(before)

(change made)

(after)

3). If you want to point to different stylesheets for different report executions (ie. if you need security and want to hide the Save or Print button from some users), you can easily do that by adding the filename of your own custom stylesheet to the rc:Stylesheet parameter in the SSRS Request URI a la:


Other things like client-side scripting can be done to extend the Report Viewer UI further, but doing that sort of "functionality" integration is not well documented. If you want complete control over your Reporting Services app UI, take a look at the Report Server web service: https://docs.microsoft.com/en-us/sql/reporting-services/report-server-web-service/report-server-web-service

Happy Reporting!

Useful T-SQL Dates Reference

For short US datetime format use this:

select convert(varchar, getDate(), 1) --10/15/2017

For a list of most others (SQL Server), see: https://rauofthameem.wordpress.com/2012/09/14/sql-date-time-conversion-cheat-sheet/

On to the useful SQL dates:

select dateadd(mm, datediff(mm, 1, getDate()), 0) as FirstaTheMonth

select dateadd(ms, -3, dateadd(mm, datediff(m, 0, getDate()) + 1, 0)) as LastaTheMonth

select dateadd(qq, datediff(qq, 0, getDate()), 0) as FirstDayOfQtr

select dateadd(wk, datediff(wk, 0, dateadd(dd, 6 - datepart(day, getDate()), getDate())), 0) --(First Monday of Month)





Great T-SQL References:

http://www.gehbeez.com/sql-get-first-and-last-day-of-a-week-month-quarter-year/

http://brianvanderplaats.com/cheat-sheets/T-SQL-Cheat-Sheet.html

TDD in small, digestible chunks

Test-Driven Development becomes (necessarily) much more common as code bases grow larger, diverse and more mission critical. Every piece of logic that can be explained in your software's documentation should be testable.

Write the tests, then write the code to meet those conditions, refine, repeat

Though 100% code-coverage is rarely attainable, the closer to fully covered with unit and integration tests, the more secure and solidly structured the code will be. Moreover, the dependency nightmares that many teams wrestle with will be largely mitigated as code reliability checks take place daily when TDD is fully embraced and implemented well.

I am assuming you know the basics of "why" and "how" TDD is done. If TDD does not feel natural, you may want to check out the book Test-Driven Development by Kent Beck. Reading that, what was most impressionable to me and has aided my TDD development style are the following quotes:

"Return a constant and gradually replace constants with variables until you have the real code". -on testing complex functions or objects
 
 "Write tests you wish you had. If you don't- you will eventually break something while refactoring". -on code bases with limited test coverage.

Do not write a few large tests to evaluate multiple ideas/functions at once. Write many small tests that test something that can be said in one short sentence: "Password Reset form successfully sends Reset email to appropriate user".




Write all the tests you know you will need and the tests you wish you had. You will wind up with quite a lot of code, but also quite a lot of "proofs", and you will be able to more confidently add to and refactor your highly-maintainable TDD-developed code.

Python 3 for fun - Screen Scraping



Download Python 3: https://www.python.org/downloads/

Open cmd, type: python

from lxml import html
import requests

#Initialize your page and tree list variables
page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)

See your page variable's output:
(Excerpts taken from Python.org, I've updated the instructions for Python 3+)

#This will create a list of buyer elements from the DOM (divs with a specific 'title' attribute):
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of price elements from the DOM (spans with a specific class):
prices = tree.xpath('//span[@class="item-price"]/text()')

print ('Buyers: ', buyers)
print ('Prices: ', prices)


Expected output:

You can get a lot of useful things done in Python with relatively few lines of code.

SQL NULL cannot be applied to arithmetic operations (select NULL > 1 = NULL)


"Any arithmetic expression containing a null always evaluates to null. For example, null added to 10 is null." -http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements005.htm#i59110

In SQL Server, this behavior can result in string concatenation failing due to one of the values being NULL, which, as is NULL's nature, turns the entire variable into NULL.



....results in: NULL

Two easy ways to work around* the inability to evaluate NULL are as follows:
 (COALESCE takes first non-NULL value specified whereas ISNULL takes just one alternate value)

Different database platforms have different rules for NULL but arithmetic ops will not work in any, as NULL is only ever NULL, and NULL is an unknown. If you are checking for the existence of data, you should be using:


select top 5 m.Column1 FROM MYTABLE m WHERE m.Column1 IS NOT NULL


*you can do this in lieu of not getting bad data in the 1st place, obviously- if the column in question needs to hold a legitimate numeric value for calculation.. your app probably should not be generating and storing null values into that column.

Invisible characters from pasted data



If you find yourself debugging an ETL task error where the problem at hand is data type mismatch or some other data error that is not visible to you in the source (culprit) data, don't fret.

What has likely happened is invisible formatting characters got into the data.

To remedy things, all you'll need to do is open up Notepad++, paste your data into the text window, and from the View menu dropdown, select "Show Symbol" >> "Show All Characters".

Simply edit the data in Windows Notepad (remove the special characters), save, and try to import again. Your data should be sufficiently scrubbed clean and your ETL task will return to normal.


There is also a shortcut button in Notepad++:


PS: handy tip for Windows users- to remove all formatting from copied data, paste the text into Notepad. All formatting will be removed from the data. Re-select it and go paste where needed.

PureText is another application that handles removing all formatting from text: https://stevemiller.net/puretext/

Developer Scratchpad (.NET C#, VB, JavaScript, Powershell, Python, SQL, etc.)

If you memorize infrequently used code, you are wasting mental storage space- reference notes!



--------NETWORK-----------------------------------------------------------
--------------------------------------WINDOWS BUILTIN CMDs-------------------------------------
//converting Windows back slashes to Unix forward slashes
SET string=C:\Users\Admin\Desktop\DeskDEV\
ECHO %string:\=/%
//converting Unix forward slashes to Windows back slashes
SET string=C:/Users/Admin/Desktop/DeskDEV/
ECHO %string:/=\%
netsh interface ip show config
netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.254
netsh interface ip set address "Local Area Connection" dhcp
netsh http show urlacl
netsh int tcp set heuristics disabled
netsh int tcp set global autotuninglevel=disabled
netsh int tcp set global rss=enabled
netsh int tcp show global
netsh winsock reset
netsh int ip reset
ipconfig /release
ipconfig /renew
ipconfig /flushdns
ipconfig /registerdns
msdt.exe -id NetworkDiagnosticsWeb
msdt.exe -id NetworkDiagnosticsInbound
msdt.exe -id NetworkDiagnosticsNetworkAdapter
ipconfig
sfc /scannow
driverquery
ping and pathping
tasklist and taskkill
nslookup
sigverif
doskey /history
netstat
cipher
getmac
net user
arp
nbstat
logman
route
shutdown
assoc
schtasks
attrib
auditpol
bcdboot
bcdedit
bootcofg
bootsect
cacls
call
cd
certreq
certutil
chcp - (active code page)
checknetisolation
chkdsk
chkntfs
choice - ([Y,N]? prompt in .bat)
cipher - (enc status of files)
clip
cls
cmstp - (connectionMgr interesting*)
comp - (basic file diff)
compact - (compress)
convert - (file system type)
copy
cscript - (execute vbs, etc.)
date
debug - (only on DOS && 32bit Windows)
defrag
del
deltree
dir
diskpart*
diskperf
diskraid
dism - (dply .isos)
dispdiag
djoin - (join domain)
driverquery - (all driver information!)
echo
endlocal - (break out of a script's localalized context)
erase
esentutl - (storage engine mgmt)
eventcreate
expand - (unzip archive)
Extrac32 - (unzip .cab)
extract - (unzip archive)
fc - (compare file sets)
find - (srch for text in file or files)
Findstr - (regex "")
finger - user(s) info
Fltmc - (filter driver installer)
fondue - (new/experimental Windows features)
format - (format drive for some file system)
fsutil - (filesys utiles)
ftp - (chell for ftp comms; "quit")
ftype - default programs
getmac - get MAC of all network controllers on system
gpresult - (grp policy)
gpupdate
icacls
iscsicli - (iSCSI initiator)
klist - Kerberos tickets
Ksetup - (for a kerberos-enabled server)
ktmutil - (kernal transaction mgr utility)
label - (volume label of disks)
licensingdiag - (Windows product activation info)
loadhigh(lh), lock - (old DOS cmds)
lodctr - (registry values for perf counters)
logman - (event trace session)
logoff - (until Win7)
makecab - (cainet maker)
manage-bde - (Bitlocker drive enc)
mklink - (create symbolic link)
mode - (COM/LPT ports - check "CON" device further)
mofcomp - .mof* file display
more
mount - (until SFU was discontinued...)
mountvol - (use this instead)
move
mrinfo - (rounter info)
msg
msiexec - (start an install)
muiunattend - (unattended install)
nbtstat - (see connection info)
net - (cfg network settings)
net1 - ("" "" Y2K issue wkrnd/patch for net)
netcfg - (installs WinPE)
netsh - (network shell, net mgmt)
netstat - (displays listening ports, connects)
nltest - (test secure channels between machines across trusted domains)
nslookup - (hostname from IP)
openfiles - (remote cmd)
path
pathping - (tracert w/net latency, more info)
pause - (Press any key to continue...)
ping
pkgmgr - (windows pkg mgr)
pnpunattend - (unattended driver install)
pnputil
popd
powercfg
print
prompt
pushd
rasautou
rasdial*
rcp - (deprecated)
rd
reagentc - (win recovery)
recover - (recover a file deleted, but not yet overwritten)
reg - (registry cmds)
regini - (hange registry permissions and registry values from the command line)
Regsvr32 - (register .dll as component)
relog - (new perf append to existuing perf data)
rem
ren
repair-bde - (Bitlocker repair)
replace
rmdir
robocopy - (robust copy)
route - (maniupulate network routing tables)
Rpcping
runas
schtasks
sdbinst - (SDB db files, used by OpenOffice)
secedit - (compare current sec levels to a template to ensure no unneeded access, etc.)
setspn - (set service principle name for an AD account)
setx - (user env variable config)
sfc - (System File Checker)
shutdown - (automate poweroff)
sort
sxstrace - tracing
subst - (assoc local path with drive letter; similiar to net use)
takeown - regain access to object
taskkill - (force kill a process)
tasklist - (running proccesses; used by taskmgr.exe, etc.)
tcmsetup - (to set up or disable the Telephony Application Programming Interface (TAPI) client)
telnet
tftp (deprecated?)
time
timeout
title - (cmd prompt window label)
tracerpt - trace rpt
tracert - Internet Control Message Protocol (ICMP) Echo Request messages to a specified remote computer with increasing Time to Live (TTL) field values and displays the IP address and hostname, if available, of the router interfaces between the source and destination.
tree - (awesome)
typeperf - (cmd perf data)
tzutil - (time zones)
unlodctr - (uninstalls a perf counter in registry)
vaultcmd - (manage Windows stored creds)
ver
vol
vssadmin - (volume shadow copy admin)
w32tm - (windows time)
wecutil - (win evt collector)
where - (find by regex)
whoami
winmgmt - (WMI)
winrm - (remote mgmt)
winrs - (remote sh)
winsat - (system assesment tool)
wmic - (WMI CLI)
wsmanhttpconfig
xcopy
xwizard - (register data in Windows, often from a preconfigured XML file)


-------POWERSHELL---------------------------------------------------
Get-Command -Name {..}
get-alias
Get-Help Get-EventLog
Get-ChildItem c:/
$var
(no concept of scope- ALL is glbl)
Remove-Item
//ex. of getting some scv column data...
Get-Command -Verb Export | Select-Object CommandType, Name, Version, Source | Export-Csv -NoTypeInformation -Path C:\NewFolder\ExportCommands.CSV
//Outfile is useful
Get-Command -Verb Export | Select-Object CommandType, Name, Version, Source | Out-File C:\NewFolder\ExportCommands.txt
Get-Process -Id 10500 | Stop-Process
Get-EventLog -LogName System -Newest 5
Clear-EventLog "Windows PowerShell"
Get-WmiObject -List -Class Win32*
Enter-PSSession Computer1
Invoke-Command -ComputerName Computer1, Computer2, Computer3, -ScriptBlock {Get-Process}
//Create a new (persistant) session, and save it
$session = New-PSSession -ComputerName Computer1, Computer2
Set-ExecutionPolicy
Get-ExecutionPolicy
Get-Service | Where-Object {$_.status -eq "stopped"}
//Create html from basic data structs (in this case, ps cmdlet aliases)
get-alias | convertto-html > aliases.htm
invoke-item aliases.htm
Get-EventLog -Log "Application"
Stop-Process -processname note*
Get-Service | Where-Object {$_.Status -eq 'Running'}
Get-AuthenticodeSignature somescript.ps1 @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] -IncludeChain "All" -TimestampServer "http://timestamp.verisign.com/scripts/timstamp.dll"
Get-Process | ForEach-Object {Write-Host $_.name -foregroundcolor cyan}
Clear-Content C:\Temp\TestFile.txt
Clear-Content -path * -filter *.TXT –force (all text files force clear)
Checkpoint-Computer -Description "My 2nd checkpoint" -RestorePointType "Modify_Settings"
Get-ComputerRestorePoint | format-list
Compare-Object $obj1 $obj2
 [string[]]$arrayFromFile = Get-Content -Path 'C:\someplace\file.txt'
 foreach ($uri in $arrayFromFile) {
   yt-dl -f 140 $uri
  }
$settings = $TextData | ConvertFrom-StringData
ConvertTo-SecureString [-String] SomeString
Get-Service wuauserv -ComputerName chi-dc04,chi-p50,chi-core01 |
Export-Clixml -Path c:\work\wu.xml
Get-AppLockerPolicy
New-ItemProperty
$ourObject = New-Object -TypeName psobject
/////////////////////////////////////////////////////
$url = http://<webapp>.azurewebsites.net/CreateSite.asmx
$proxy = New-WebServiceProxy $url
$spAccount = "<username>"
$spPassword = Read-Host -Prompt "Enter password" –AsSecureString
$projectGuid = ""
$createOneNote = $false
$proxy | gm -memberType Method
New-WSManInstance winrm/config/Listener
-SelectorSet @{Address="*";Transport="HTTPS"}
-ValueSet @{Hostname="Test01";CertificateThumbprint="01F7EB07A4531750D920CE6A588BF5"}
/////////////////////////////////////////////////////
Get-Process | Sort-Object name -Descending | Select-Object -Index 0,1,2,3,4
New-Alias np c:\windows\system32\notepad.exe
Set-StrictMode
Wait-Job
Write-Progress -PercentComplete (($var1/$var2) * 100))
$job = Start-Job -ScriptBlock { Set-PSBreakpoint C:\DebugDemos\MyJobDemo1.ps1 -Line 8; C:\DebugDemos\MyJobDemo1.ps1 }
Debug-Job $job
Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 3
Test-Path C:\Scripts\Archive
Get-WinEvent -ListLog *
Invoke-TroubleshootingPack (Get-TroubleshootingPack C:\Windows\diagnostics\system\networking)
Measure-Command
Get-Process | Measure-Object VirtualMemorySize -Sum
New-EventLog -LogName Wtf_Log -Source SomewhereOutThere
Receive-Job -Name HighMemProcess
Register-EngineEvent PowerShell.Exiting -Action {"PowerShell exited at " + (Get-Date) | Out-File c:\log.txt -Append}
Register-ObjectEvent
Remove-Event
Set-PSDebug
Start-Sleep
Tee-Object
Test-AppLockerPolicy
Test-ComputerSecureChannel
Trace-Command
Write-Debug "`$return has $($return.count) items"

-------VISUAL STUDIO----------------------
Ctrl+, . for Autosuggest
Sort usings by Right-click on using references

--------.NET------------------------------------------------------
--------------------------C#--------------------------------------
//switch expression*
car foo = line switch {
case 0: foo = 1; break;
case 0: foo = 1; break;
default: for = 0; break;
}
XDocument.Parse is for string XML
XDocument.Load is for XML *Files*
[,] is multidimensional array and [][] is array of arrays.
//collection initializer
List<Coord> ls = new List<Coord>() { new Coord { x = 1, y = 2 }, new Coord { x = 11, y = 12 }};
//lambda expression value
var filteredList = list.Where(o => o.id == targetGUID);
//Make the internals visible to the test assembly for unit testing private dependencies, etc.
[assembly: InternalsVisibleTo("MyTestAssembly")] in the AssemblyInfo.cs file.
//Obsolete attribute to warn that an assembly may go away and that alternatives should be used asap
Obsolete("This method will be deprecated soon. You could use XYZ alternatively.")]
//To prevent a repetition of the execution, change the LINQ result to List after execution
var result = masterCollection.Where(i => i > 100).ToList();
Console.WriteLine(result.Count()); //no extra Linq executions
Console.WriteLine(result.Average()); //no extra Linq executions
//catch Generic Exception and throw for more detail
catch (Exception)
      throw;
//Generic Type using a common Interface
protected class MyGenricClass<T> where T : IMyInterface
public void MyGenericMethod<T>(T t) where T : IMyInterface
//using obj reference for brevity and cleaner code
using (SqlConnection conn = new SqlConnection(strConnection)) { ... }
//aslias namespaces for brevity if you need to explicitly spell out the namespace anywhere
using Excel = Microsoft.Office.Interop.Excel;
var excelapp = new Excel.Application();
//object initializer
Janitor jenkins = new Janitor() { Name = "Jenkins", Address = "1212 DeplPipelnSciptzzz" };
//null checks
if (string.IsNullOrEmpty(s))
//Connection String
"Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"
//Entity Framework Optimizer/Escape Hatch
using (var db = new MyContext())
{
    db.Query<FooBar>().FromSql("SELECT ProductID, udf_GetNameFromId(ID3) FROM Products");
}
//JSON Serialize and Deserialize with Newtonsoft
string serial = JsonConvert.SerializeObject(genericObject);
var deserial = JsonConvert.DeserializeObject<APIGenericItemsResponse>(await response.Content.ReadAsStringAsync());
//XML Serialize using System.Xml.Serialization
 public void TestSerialize(XMLEntityCollection ents)
     {
       XmlSerializer xmlSerializer = new XmlSerializer(ents.GetType());
       using (StringWriter stringWriter = new StringWriter())
       {
         xmlSerializer.Serialize(stringWriter, ents);
         Assert.IsNotNull(stringWriter);
       }
     }
//XML Deserialize using System.Xml.Serialization
XmlSerializer serializer = new XmlSerializer(typeof(XMLEntityCollection));
       using (StringReader reader = new StringReader(xml))
       {
         XMLEntityCollection ents = (XMLEntityCollection)serializer.Deserialize(reader);
         TestSerialize(ents);
       }
-------------------------VB--------------------------------------
Dim i As Integer = 1
Begin Function(ByVal a As String) As Double
     Return 37
End Function
Namespace MyNamespace
End Namespace
Public Class Manager
     Inherits Employee
End Class
Public Overridable Function CalculateSalary() As Integer
End Function
Public Overrides Function CalculateSalary() As Integer
End Function
MyBase (base in C#)
Public Interface IEmployee
    Property EmployeeID() As Integer
    Property Name() As String
    Property Age() As Integer
    Function CalculateSalary() As Integer
End Interface
Public Class Manager
Implements IEmployee
End Class

--------PYTHON-----------------------------
#cool-youtube-API
youtube-dl -f 140 $uri
#formatting opts for youtube-dl

[info] Available formats for P9pzm5b6FFY:
format code extension resolution  note 
140         m4a       audio only  DASH audio , audio@128k (worst)
160         mp4       144p        DASH video , video only
133         mp4       240p        DASH video , video only
134         mp4       360p        DASH video , video only
135         mp4       480p        DASH video , video only
136         mp4       720p        DASH video , video only
17          3gp       176x144     
36          3gp       320x240     
5           flv       400x240     
43          webm      640x360     
18          mp4       640x360     
22          mp4       1280x720    (best)
#reverse string
a =  "NotPalindrome"
print("Reverse is",a[::-1])
#transpose matrix
mat = [[1, 2, 3], [4, 5, 6]]
zip(*mat)
#store array as indiv vars
a = [1, 2, 3]
x, y, z = a
#print array elments as string
a = ["This", "is", "a", "string"]
print(" ".join(a))
#print coords of 2 combined lists
list1 = ['a', 'b', 'c', 'd']
list2 = ['p', 'q', 'r', 's']
for x, y in zip(list1,list2):
...    print(x, y)
#switch var vals in 1 line
a=2
b=4
b, a =a, b
#execute recursion without loops
print("cool"*2+' '+"beans"*5)
#convert matrix to list without loop
import itertools
a = [[1, 2], [3, 4], [5, 6]]
list(itertools.chain.from_iterable(a))

-------JAVASCRIPT------------------------------------
//Use "var" or "let" when creating any variables Assignment to an undeclared variable automatically //results in a global variable being created. Avoid global variables.
var a = 'not Globl';
=== instead of == (former compares value and type)
//Be careful when using typeof, instanceof and constructor.
var arr = ["a", "b", "c"];
typeof arr;   // return "object"
arr  instanceof Array // true
//get random item from an array
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var  randomItem = items[Math.floor(Math.random() * items.length)];
//get random number in a specific range
var x = Math.floor(Math.random() * (max - min + 1)) + min;
//Trim String prototype extension function
String.prototype.trim = function(){return this.replace(/^s+|s+$/g, "");};
//Append array to array
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
//Object to Array
var argArray = Array.prototype.slice.call(arguments);
//Verify numeric
function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}
//verify Array type
function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}
//Max and Min
var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
//Empty the array
var myArray = [12 , 222 , 1000 ];
myArray.length = 0;
//use splice() not delete() for removing JS array elements
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
//use map() to loop through array
var squares = [1,2,3,4].map(function (val) {
    return val * val;
});
//rounding a decimal numeric
var num =2.443242342;
num = num.toFixed(4);
//check object props
for (var name in object) {
    if (object.hasOwnProperty(name)) {
        // do something with name                 
    }
}
//Serialize and Deserialize
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object  */
//Best/fastest JS looping structure
var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i++) {
    sum += arrayNumbers[i];
}
//Pass functions (not string ref of function) to SetTimeout() and SetInterval()
setInterval(doSomethingEverySecond, 1000);
setTimeout(doSomethingEveryFiveSeconds, 5000);
//Clone a type
function clone(object) {
    function OneShotConstructor(){};
    OneShotConstructor.prototype= object;
    return new OneShotConstructor();
}
clone(Array).prototype ;  // []
//HTML escape function
function escapeHTML(text) {
    var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", """: "&quot;"};                   
    return text.replace(/[<>&"]/g, function(character) {
        return replacements[character];
    });
}
//Set timeouts on async function calls
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
    if (this.readyState == 4) {
        clearTimeout(timeout);
        // do something with response data
    }
}
var timeout = setTimeout( function () {
    xhr.abort(); // call error callback
}, 60*1000 /* timeout after a minute */ );
xhr.open('GET', url, true);

xhr.send();

//deal with websocket timeout
var timerID = 0;
function keepAlive() {
    var timeout = 15000;
    if (webSocket.readyState == webSocket.OPEN) {
        webSocket.send('');
    }
    timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
    if (timerId) {
        cancelTimeout(timerId);
    }
}

-------T-SQL-----------------------------------------------------------
SELECT dateadd(mm, datediff(mm, 1, getDate()), 0) as FirstOfTheMonth
SELECT dateadd(ms, -3, dateadd(mm, datediff(m, 0, getDate()) + 1, 0)) as LastOfTheMonth
SELECT dateadd(qq, datediff(qq, 0, getDate()), 0) as FirstDayOfQtr
SELECT dateadd(wk, datediff(wk, 0, dateadd(dd, 6 - datepart(day, getDate()), getDate())), 0)  --(First Monday of Month)
--Find all instances of a 'string' within a string (varchar/nvarchar)
CREATE FUNCTION dbo.FindPatternLocation
(
    @string NVARCHAR(MAX),
    @term   NVARCHAR(255)
)
RETURNS TABLE
AS
    RETURN
    (
      SELECT pos = Number - LEN(@term)
      FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@string, Number,
      CHARINDEX(@term, @string + @term, Number) - Number)))
      FROM (SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
      FROM sys.all_objects) AS n(Number)
      WHERE Number > 1 AND Number <= CONVERT(INT, LEN(@string)+1)
      AND SUBSTRING(@term + @string, Number, LEN(@term)) = @term
    ) AS y);
--Windowing for running totals, referencing related rows and row group totals
SELECT xact_amt,
     SUM(xact_amt) OVER (ORDER BY xact_datetime) AS running_total
FROM SOME_DB.dbo.SOME_TABLE
 --Get ids from a csv of ids
 SELECT * FROM string_split('100,101,201,301,411,414', ',')
--Push a series of values into one row
 SELECT playerID,
 STUFF((select '; ' + teamID
      from Managers
      where teamID like('%P%')
            group by teamID
      for xml path('')), 1, 1, '') allTeams
 FROM Managers
--Dynamic SQL
 DECLARE @mult bit = 0
 DECLARE @sqlToExecute varchar(500)
 DECLARE @srvWest varchar(50) = 'WestZoneSqlSrv08'
 DECLARE @srvEast varchar(50) = 'EastZoneSqlSrv08'
 IF @mult = 0
      SET @sqlToExecute = 'SELECT TOP 1 OrderId, PersonId FROM ALGO.dbo.[Order]'
 ELSE
      SET @sqlToExecute = 'SELECT TOP 1 OrderId, PersonId FROM ' + @srvEast + '.ALGO.dbo.[Order] UNION ALL SELECT TOP 1 OrderID, PersonId FROM ' + @srvWest + '.ALGO.dbo.Order' 
 EXEC(@sqlToExecute)
--CTE
WITH Entity (EntityID, Name, ParentID, Tree)
AS
(
   SELECT ID, Val1, Val2 FROM SomeDbServer.dbo.SomeDatabase;
)

SELECT * FROM Entity;

-------GIT------------------------------------------------------
git log
git diff
git init
git branch
git branch -a
git branch <branchname> ((new branch))
git switch <branchname> ((same as checkout))
git merge <branchname> ((merge another branch into current working branch))
git push origin <branchname>
git push -u origin <branchname>
git pull origin <branchname>
git remote add origin <ssh or https URI>

--------WinDbg--------
!sos.threadpool (Strike subset of modules useful (yet safe) for debugging .NET)
!sos.savemodule
!sos.finalizequeue
!mex.us
!mex.aspxpagesext
!mex.mthreads / !sos.threads
!mex.dae
!mex.clrstack2

!sym noisy
g - (Go)
r - (Registers)
d - (virtual memory commands)
!teb - (thread environment block)
!peb - (process execution block)
~{thread id}|| ~*k to execute "each thread" and assoc k cmd on them
k - (look at stacks in debugger => top is end, bottom is init/start 00000000)
? - (evaluation cmd to get HEX equiv)
lm (loaded modules (lm v m malware => show verbose module (m)atching 'malware'))
du - (display Unicode value)
.crash - (forces blue screen crash and .dmp)

-------REGEX--------------------------------------------------
(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
File Path with Filename and extension
/((\/|\\|\/\/|https?:\\\\|https?:\/\/)[a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]+)+\.[a-z]+$/
 File Path with optional Filename, extension
/^(.+)/([^/]+)$/
File Name with extension having 3 chars
/^[\w,\s-]+\.[A-Za-z]{3}$/
/* Match IPv4 address */
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/
/* Match IPv6 address */
/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/
/* Match both IPv4, IPv6 addresses */
/((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/
Elements with Attributes /<\/?[\w\s]*>|<.+[\W]>/
Slug /^[a-z0-9]+(?:-[a-z0-9]+)*$/
Digits
    Whole Numbers – /^\d+$/
    Decimal Numbers – /^\d*\.\d+$/
    Whole + Decimal Numbers – /^\d*(\.\d+)?$/
    Negative, Positive Whole + Decimal Numbers – /^-?\d*(\.\d+)?$/
    Whole + Decimal + Fractions – /[-]?[0-9]+[,.]?[0-9]*([\/][0-9]+[,.]?[0-9]*)*/
Alphanumeric without space – /^[a-zA-Z0-9]*$/
Alphanumeric with space – /^[a-zA-Z0-9 ]*$/
Common email Ids – /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/
Uncommon email ids – /^([a-z0-9_\.\+-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
Password Strength
Complex: Should have 1 lowercase letter, 1 uppercase letter, 1 number, 1 special character and be at least 8 characters long
/(?=(.*[0-9]))(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?])(?=.*[a-z])(?=(.*[A-Z]))(?=(.*)).{8,}/
Moderate: Should have 1 lc letter, 1 UC letter, 1 number, and be at least 8 characters long
/(?=(.*[0-9]))((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.{8,}$/
/* Username */
    Alphanumeric string that may include _ and – having a length of 3 to 16 characters –
    /^[a-z0-9_-]{3,16}$/
/* Date Format YYYY-MM-dd */
/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
    Time Format HH:MM 12-hour, optional leading 0
    /^(0?[1-9]|1[0-2]):[0-5][0-9]$/
    Time Format HH:MM 12-hour, optional leading 0, Meridiems (AM/PM)
    /((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
    Time Format HH:MM 24-hour with leading 0
    /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    Time Format HH:MM 24-hour, optional leading 0
    /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    Time Format HH:MM:SS 24-hour
    /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/


/* PowerShell has interesting return value behavior; vars are kept in global scope unless explicitly removed
$a = "Hello, World"
return $a
$a = "Hello, World"
$a
return */

-------DATA LAKE--------
Intermittent data holding area; a function of time restrictions, best for unstruct'd data/Ops Log/Config Data....... (for monitoring apps before a problem happens or gets worse)



References:

https://modernweb.com/45-useful-javascript-tips-tricks-and-best-practices/

https://pythontips.com/2015/04/19/nifty-python-tricks/#more-580

https://www.freelancer.com/community/articles/top-16-c-programming-tips-tricks

https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/inheritance 

https://www.debuggex.com/

https://digitalfortress.tech/tricks/top-15-commonly-used-regex/