Bash Primer

About Bash

Bash is the GNU Project’s shell. Bash is the Bourne Again SHell. Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard. It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification.
https://www.gnu.org/software/bash/

Running Bash on Mac OSX

For this primer we will be using a text editor to write the .sh file and executing them via Terminal. In Finder, search for “Terminal” and select Terminal from Applications.

Running .sh Files via Terminal

The first line contains a shebang #! followed by the path to the shell, in this case bash – this acts as an interpreter directive and ensures that the script is executed under the correct shell.
http://ss64.com/osx/syntax-shellscript.html

  1. Open Terminal
  2. Enter chmod u+x {scriptName}.sh and press enter
    • chmod changes the access permissions
    • u = User Permission
    • x = Execute
  3. Enter ./{scriptName}.sh and press enter
    • dot slash (./) is used in Linux and Unix to execute a compile program in the current directory
    • You can setup a PATH so that you do not have to enter the dot slash every time

Hello World!

echo
Display message on screen, writes each given STRING to standard output, with a space between each and a newline after the last one.
http://ss64.com/bash/echo.html

  1. Open Terminal
  2. Type echo 'Hello World!'
"Hello World!"

Variables

You can use variables as in any programming language. There are no data types. A variable in bash can contain a number, a character, a string of characters.
You have no need to declare a variable, just assigning a value to its reference will create it.
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-5.html

In the Unix/Linux shell (bash/sh), ‘$’ is a unary operator, used for parameter expansion, replacing the name of a variable by its (sometimes modified) value.
http://en.wikipedia.org/wiki/Unary_operation#Unix_Shell_.28Bash.29

NOTE – Regarding variables:

  1. Instantiate your variable without the unary operator ($)
  2. Do not use spaces in setting the value
  3. Call your variable with the unary operator ($)
#!/bin/bash
message='Hello World!'
echo $message
"Hello World!"

Functions

Like “real” programming languages, Bash has functions, though in a somewhat limited implementation. A function is a subroutine, a code block that implements a set of operations, a “black box” that performs a specified task. Wherever there is repetitive code, when a task repeats with only slight variations in procedure, then consider using a function.
http://tldp.org/LDP/abs/html/functions.html

#!/bin/bash
message='Hello World!'
Write-Message ()
{
	echo $message
}
# Call the function
Write-Message
Hello World!

Passing Variables to Functions

Previously, message was accessible because its scope was Global. You can pass variables and values to functions by appending those values to the function call. Also, your function must expect a value. In this example, we pass a string into the function that is assigned a numerical value (the first argument is $1). Use $# to assign the passed in argument to a local variable.

#!/bin/bash
Write-Message ()
{
	local message=$1
	echo $message
}
# Call the function
Write-Message 'Hello World!'
Hello World!

Error Handling

Bash doesn’t have Try…Catch like PowerShell. So, I have tried to frame out how that could be addressed manually. In the example below I pass commands as strings to a Try() function and if that command returns an error it will be caught and addressed in a Catch() function.

#!/bin/bash
Write-Message ()
{
	# Pass the command as a string to Try()
    Try 'echo Hello World!'
	# Pass a string that will cause $1 to not equal 0
	Try 'false'
}
Try ()
{
	# Run first parameter (string) as a command
	$1
	# Was the EXIT code not equal to 0?
	if [ $? -ne 0 ]
	then
		# Catch the error by performing some action
		Catch
	fi
}
Catch ()
{
	# Handle the exception
	echo "Exception!"
}
finally ()
{
	# Perform some final task before the script ends
	echo "Script Complete."
}
# Call the function
Write-Message
# Trap the call to EXIT and run finally()
trap finally EXIT
Hello World!
false: command not found
Exception!
Script Complete.

Further Reading

Advanced Bash-Scripting Guide

  • An in-depth exploration of the art of shell scripting by Mendel Cooper

Linux Shell Scripting Tutorial (LSST) v2.0

  • This book is created and maintained by Vivek Gite – a Sr. UNIX admin.

An A-Z Index of the Bash command line for Linux

  • SS64 has compiled an alphabetical list of Bash commands.

Automated Software Testing Tools

About Automated Software Testing

In software testing, test automation is the use of special software (separate from the software being tested) to control the execution of tests and the comparison of actual outcomes with predicted outcomes. Test automation can automate some repetitive but necessary tasks in a formalized testing process already in place, or add additional testing that would be difficult to perform manually.
http://en.wikipedia.org/wiki/Test_automation

Picking the Right Tools for the Job

There is no one-size-fits-all solution. You will need to take into consideration:

  • End-users device; Desktop and/or mobile?
  • (Web Applications) Web browsers
  • Technology used to make the tested application (ASP, WinForms, etc.)
  • Size of QA Team
  • Size of QA Automation Team
  • Price

What makes an automation tool good? Here are my thoughts:

  • Usability
    • Buttons and options are tidy and make sense as to their grouping
    • Programs flows like a book, left-to-right and top-to-bottom
  • Ease of Use
    • Beginners can record-and-click to create tests
    • Advanced users can write custom code
  • Productivity
    • A high purchase price is offset after a few months of test automation
    • Compare how long it takes to create and then modify a test in each tool
  • Comments
    • Each test, step, custom code has a description and/or comment

Automation Software

There are many tools in the wild but I can only speak as to the ones I have used.

These tools are good for scripting.

  • AutoIT
    • AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting.
    • Example: I made a list of URLs to browse via IE to test a toolbar for memory leaks. Monitored the toolbar process via PerfMon.
  • AutoHotKey
    • Fast scriptable desktop automation with hotkeys
    • Example: I made a script that simulated a key press every 10 seconds.
  • Chromium browser automation
    • Extension for automating chromium browser, Create project -> Record -> Edit Automation -> Manage -> Play
    • Example: I recorded myself trying to log in to a site. Played back 10 times to see if the account got locked or if the time between requests was extended after each bad attempt.
  • PowerShell
    • Comes with most Windows OS distributions
    • Supports .Net framework
    • Example: I wrote a script that copies the latest build from the build machine to each test environment and installed that latest build. The scripts also sent out an email when it successfully ran a warm-up test, telling QA the build was ready to be tested.

These tools are good for testing:

  • Selenium
    • Made by eBay using java tools
    • Can run test in JUnit or NUnit
    • Limited browser support
    • Free
  • Telerik Test Studio
    • Supports most modern browsers
    • Supports Silverlight and WPF applications
    • Framework is available for free
    • Integrates with TFS
  • Microsoft Test Manager
    • Part of Visual Studio (Test Professional, Premium or higher)
    • Same browser support of Selenium
    • Test plan and test case repository

Recommendations

For scripting, I prefer PowerShell. It is fully supported by Microsoft and comes pre-installed on most Windows OS deployments.

For testing, I prefer Test Studio. It has quarterly releases by Telerik and hits all the right notes in what I consider a good tool.

Why Telerik Test Studio?

  • Usability
    •  Layout is clear and familiar (follows MS Office lead)
  • Ease of Use
    • Beginners can record-and-click to create new tests. They can also edit tests, like modify the find logic of an html element, rather easily.
    • Advanced users can write custom code in VB or C#.
  • One environment
    • In Selenium you need separate programs to create, edit, and playback test.
    • In Test Manager you need to have Visual Studio Pro (or higher) to convert test cases from recorded actions to automated tests.
  • Compatibility
    • Browsers: Internet Explorer, Chrome, Firefox, Safari
    • Application Platforms: Silverlight and WPF
  • Productivity
    • Tests and created and modified quickly.
  • Comments
    • Each Test and Test List has a description. Each Test Step can be commented or have its description altered.

Was there a close second?

Microsoft Test Manager is evolving with each iteration and could come to surpass HP’s Quality Center for enterprise solutions. It could overtake Telerik if it lets the Test Professional edition write automated tests and those tests are in a separate solution for the application.

Strengths

  • Test plans and test cases are saved as part of the project
  • Manual testing has great features
    • Sidebar to step through test cases and mark as pass or fail
    • Take photos or videos of testing
    • Attach bugs in TFS

Weaknesses

  • Fragmented IDE requirements
    • Must have Test Professional to make tests but must have Visual Studio Professional (or higher) to convert tests to automation
  • Limited browser support
  • High initial cost

Best Practices

  •  Try not to rely on existing data
    • Your data will typically be wiped when a new build is deployed or when a vm is snapshot reverted
  • Check for dependencies
    • Do not fail an automated test that deletes a record if the record cannot be found.
      • This is a setup issue. The functionality is not being tested, only it’s error handling.
  • One failed test should not invalidate the rest of testing
    • Because the homepage test fails does not mean you can’t test other pages
  • Do not leave artifacts
    • Added a record? Why not modify it and then delete it to?
      • This will test CRUD operations
  • Try not to rely on known IDs
    • Data can be  entered in asynchronously or tests ran out of order
    • Instead try to look up the information first, see Check for dependencies (above)
  • Make test independent
    • Test 1: Login
    • Test 2: Login and Add Record
      • A test list that run Test 1 then Test 2 will run the login code twice.
        • This will add time to the overall test time
        • This will allow you to run the test individually after a test list fails
  • Use modular test and code
    • Never repeat code, instead write a module or function to handle things like logging on

Security Software

OWASP offers an incredible security tool, called Zed Attack Proxy. Beginners can simply enter the URL to their web application and click go.

Manual Software Testing Primer

About Software Testing

Software testing is an investigation conducted to provide stakeholders with information about the quality of the product or service under test. Software testing can also provide an objective, independent view of the software to allow the business to appreciate and understand the risks of software implementation. Test techniques include, but are not limited to the process of executing a program or application with the intent of finding software bugs (errors or other defects).
http://en.wikipedia.org/wiki/Software_testing

Test Environment

The environment in which you will test is likely predetermined by the QA team, Development team, or the Infrastructure team. Use of virtual machines (vm) is standard practice. Virtual machines allow you to pre-configure an environment (OS/Software combo) and save as a snapshot. A tester can fire up the vm and perform his/her testing and revert the vm when finished. Use of a VM is preferred over your workstation, because you want to limit potential risk factors. VMs should contain just your software (and any dependencies) and the OS. You may also want to include some testing tools, like Fiddler.

Common VM Technologies

Testing the Application

The VM is fired up (or you have logged onto your remote testing device) and you have installed the latest build. Now what?

Verify the Build and Deployment

Here is a check list of things to check:

  • Does the application start?
    • For web application deployments, a warm-up test is recommended
      • Warm-up Test: Requests every publicly accessible page and asserts the response is 200 (OK)
        • Should be part of any deployment script
  • If the application requires a SQL connection, then verify the connection settings
    • Usually authentication is tied to a database/server, so try logging in
      • If there is an error:
        • Check the *.config file for your application in a text editor, like Notepad++
          • Inspect the connection string, verify
            • Server
            • Database
            • Authentication method
            • Authentication credentials
        • Ensure the database is online and can be connected to, by
          • (Windows) Run cmd.exe and type ping {serverName}
          • Connect to the SQL server using a browser like SQL Server Management Studio (include in SQL Server Express)
            • Drill down to {serverName}\Databases\{databaseName}\{tableName}
              • Where {tableName} is your user table
            • Right-click a table and click Select Top 1000 Rows
  • Release Builds only, also check:
    • Version Numbers: Right-click the executable, select Properties, and then select Details
    • Digital Certificates: Right-click the executable, select Properties, and then select Digital Certificates

Read more on Installation Testing

Smoke Test

Verify that the current build is worth the effort of a full test. Sometimes a build breaks so bad that you cannot perform simple tasks. These should be done first in each environment and requires co-ordination in large teams. A build could be broken in one particular OS/Software combination and the fix will require a re-factoring. In this case you wouldn’t want to continue testing in the other environments as it will change soon.

Read more on Sanity Testing and Smoke Testing

Verify functionality

This will differ widely depending on the application. Hopefully there is already some documentation for you to start.

Testing from here is split into two categories:

  • Functional: Tests focus on the immediate task
    • Usually reserved for updating existing code
    • Example: A new login page was made
      • Test the login functionality
  • Regression: A full run of all tests
    • Usually reserved for major versions, release builds, and when code modifies a shared resource.
    • Example: A new login page was made using new session management
      • Most of your tests require an active session

Read more on Regression Testing

Exploratory Testing

When are given new code area to cover, you should try:

  1. Happy Path Testing
  2. Negative Testing
  3. Fuzz Testing
  4. Security Testing
  5. Conformance Testing (if applicable)
  6. Accessibility Testing (if applicable)
  7. Language localization (if applicable)

In all cases you should also:

Other Testing

A/B Testing: Usually done by the marketing team. QA will have tested all pages and the mechanism diverts users to one page or the other.

Acceptance Testing: The stakeholder will do some light testing after QA is finished to ensure the final product satisfactorily meets the requirements.

Performance Testing: Tests the application under various loads. Usually reserved for test automation.

Concurrent Testing

Concurrent Testing is the process of running automated tests while manual testers do exploratory testing. Any company that uses test automation, will have some sort of concurrent testing. No one should rely solely on automated tests.

Read more on Concurrent Testing

Further Reading

Software Testing

  • Wikipedia parent article of most of the links in this article

Udacity CS258

  • Software Testing Methodologies Class Online

Excel Macros Primer

About Excel Macros

The macro code language for most Office programs, including Excel, is Visual Basic for Applications (VBA). You may have recorded macros in Excel by stepping through actions that the program saves for you. When you record a macro, Excel records the VBA code describing your actions in a module attached to the workbook.
http://office.microsoft.com/en-us/training/introduction-to-terms-RZ001150634.aspx?section=3

Downloading Excel Macros

Try Office 365 Home
Office 365 gives you the power and flexibility to get things done from virtually anywhere.
http://office.microsoft.com/en-us/try/

Starting Excel Macros

IMPORTANT: This feature isn’t available in Office on a Windows RT PC.
Excel provides several ways to run a macro. A macro is an action or a set of actions that you can use to automate tasks.
http://office.microsoft.com/en-us/excel-help/run-a-macro-HA102748985.aspx

  1. Open Excel
  2. Do one of the following:
    1. Click File, click new, select New Workbook
    2. Click File, click open, select your macro-enabled workbook
  3. Click the View tab
  4. The Macros button should appear on the right side of the Ribbon(top menu bar).

Hello World!

Recording

  1. Click the Macros button on the View tab
  2. Select Record Macro…
  3. Click OK
  4. Type Hello World! in cell A1
  5. Click the Macros button again and select Stop Recording

Editing

  1. Click the Macros button on the View tab
  2. Select View Macros
  3. Select your macro from the list
  4. Click the Edit button

Your code should look something like this:

Sub Macro1()
'
' Macro1 Macro
'

'
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "Hello World!"

End Sub
"Hello World!"

Playback

  1. Clear the contents of cell A1
  2. Click the Macros button on the View tab
  3. Select View Macros
  4. Select your macro from the list
  5. Click the Run button
"Hello World!"

Variables

You often have to store values when you perform calculations with Visual Basic. For example, you might want to calculate several values, compare them, and perform different operations on them, depending on the result of the comparison. You have to retain the values if you want to compare them.
http://msdn.microsoft.com/en-us/library/cd6hcy37.aspx

Sub Macro1()
 Dim message As String
 message = "Hello World!"
 Range("A1").FormulaR1C1 = message
End Sub
"Hello World!"

Functions

All executable code must be inside a procedure. Each procedure, in turn, is declared within a class, a structure, or a module that is referred to as the containing class, structure, or module.
To return a value to the calling code, use a Function procedure; otherwise, use a Sub procedure.
http://msdn.microsoft.com/en-us/library/sect4ck6.aspx

Sub Macro1()
    ' Call the function
    writeMessage
End Sub

Sub writeMessage()
    Dim message As String
        message = "Hello World!"
    Range("A1").FormulaR1C1 = message
End Sub
"Hello World!"

Passing Variables to Functions

In this example, the function writeMessage will accept a value and declare it as a string.

Sub Macro1()
    writeMessage ("Hello World!")
End Sub

Sub writeMessage(message As String)
    Range("A1").FormulaR1C1 = message
End Sub
"Hello World!"

Error Handling

In Microsoft Excel, you can use the On Error statement in a Microsoft Visual Basic for Applications macro (Sub procedure) to trap errors and direct procedure flow to the error-handling statements in a procedure. By using error handling, you make your macros and your application easier to use by intercepting run-time errors before the user sees them.
http://support.microsoft.com/kb/141571

Sub Macro1()
    ' Run the Error handler "ErrHandler" when an error occurs.
    On Error GoTo Errhandler

    writeMessage ("Hello World!")

    ' Disable the error handler.
      On Error GoTo 0

    ' Exit the macro so that the error handler is not executed.
      Exit Sub

Errhandler:
      ' If an error occurs, display a message and end the macro.
      MsgBox "An error has occurred. The macro will end."

End Sub

Sub writeMessage(message As String)
    Range("A1").FormulaR1C1 = message
End Sub
"Hello World!"

Further Reading

Get in the Loop with Excel Macros

  • Microsoft’s training course about Excel Macros

Excel VBA Tutorial

  • Excel Easy’s VBA (Visual Basic for Applications) guide

C# Primer

About C#

C# is one of the programming languages designed for the Common Language Infrastructure. C# is built on the syntax and semantics of C++, allowing C programmers to take advantage of .NET and the common language runtime.
http://en.wikipedia.org/wiki/C_Sharp_(programming_language)

Download C#

The fastest way to start developing applications for Windows 8.1, Windows Phone, the web or the cloud. Visual Studio Express products provide a free development environment to develop applications for the latest platforms. Since it is Visual Studio, applications created in Express can be supported in other versions of Visual Studio as your needs grow.
http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx

Starting C#

Learn how easy it is to set up Visual Studio and connect to Visual Studio Online. Once you’re set up, we’ll show you how to create and organize your backlog, share your code with your team, and configure your app for continuous builds and deployment. Choose any of the sections below to get started.
http://www.visualstudio.com/get-started/overview-of-get-started-tasks-vs

Hello World!

The following procedure creates a C# version of the traditional “Hello World!” program. The program displays the string Hello World!
http://msdn.microsoft.com/en-us/library/k1sx6ed2.aspx

To create and run a console application

  1. Start Visual Studio.
  2. On the menu bar, choose File, New, Project.
  3. The New Project dialog box opens.
  4. Expand Installed, expand Templates, expand Visual C#, and then choose Console Application.
  5. In the Name box, specify a name for your project, and then choose the OK button.
  6. The new project appears in Solution Explorer.
  7. If Program.cs isn’t open in the Code Editor, open the shortcut menu for Program.cs in Solution Explorer, and then choose View Code.
  8. Replace the contents of Program.cs with the following code:
// A Hello World! program in C#.
using System;
namespace HelloWorld
{
    class Hello
    {
        static void Main()
        {
            Console.WriteLine("Hello World!");

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}
"Hello World!"

Variables

The C# typing system contains the following categories: Value types, Reference types, and Pointer types.
Variables that are value types store data, and those that are reference types store references to the actual data. Reference types are also referred to as objects. Pointer types can be used only in unsafe mode.
It is possible to convert a value type to a reference type, and back again to a value type, by using boxing and unboxing. With the exception of a boxed value type, you cannot convert a reference type to a value type.
This section also introduces void.
Value types are also nullable, which means they can store an additional non-value state. For more information, see Nullable Types.
http://msdn.microsoft.com/en-us/library/3ewxz6et.aspx

// A Hello World! program in C#.
using System;
namespace HelloWorld
{
    class Hello
    {
	string message = "Hello World!";
        static void Main()
        {
            Console.WriteLine(message);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}
"Hello World!"

Functions

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.
http://msdn.microsoft.com/en-us/library/ms173114.aspx

using System;
namespace HelloWorld
{
	class Hello
	{
		string message = "Hello World!";
		static void Main()
        	{
			// Call the method
			WriteMessage()

			// Keep the console window open in debug mode.
			Console.WriteLine("Press any key to exit.");
			Console.ReadKey();
        	}

		static void WriteMessage()
		{
			Console.WriteLine(message);
		}
	}
}
"Hello World!"

Passing Variables to Functions

Previously, message was accessible because its accessibility level is private (default). Meaning it is accessible from within the Hello class. In this example, we will pass a string value to a method as a parameter.

using System;
namespace HelloWorld
{
    class Hello
    {
        static void Main()
        {
            // Call the method
            WriteMessage("Hello World!")

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }

		static void WriteMessage(string message)
		{
			Console.WriteLine(message);
		}
    }
}
"Hello World!"

Error Handling

A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.
http://msdn.microsoft.com/en-us/library/dszsf989.aspx

using System;
namespace HelloWorld
{
    class Hello
    {
        static void Main()
        {
            try
			{
				// Call the method
				WriteMessage("Hello World!");
			}
			catch (Exception e)
			{
				// Write exception to console
                Console.WriteLine(e.Message);
			}
            finally
			{
				// Keep the console window open in debug mode.
				Console.WriteLine("Press any key to exit.");
				Console.ReadKey();
			}
        }

        static void WriteMessage(string message)
        {
            Console.WriteLine(message);
        }
    }
}
"Hello World!"

Further Reading

C# Programming Guide

  • Most of this section assumes that you already know something about C# and general programming concepts. If you are a complete beginner with programming or with C#, you might want to visit the C# Developer Center, where you can find many tutorials, samples and videos to help you get started.

.Net Pearls

  • Documentation intended to be as simple as possible. Shows examples and performance(speed, memory, etc.).

Related Reading

StackOverflow

  • If you have a question, then chances are someone else did to. Chances are if you search you question on Goggle, you will get a StackOverflow result.

 

 

T-SQL Primer

About T-SQL

Transact-SQL is central to using SQL Server. All applications that communicate with an instance of SQL Server do so by sending Transact-SQL statements to the server, regardless of the user interface of the application.
http://msdn.microsoft.com/en-us/library/bb510741.aspx

Download T-SQL

Microsoft SQL Server 2014 Express is a free, feature-rich edition of SQL Server that is ideal for learning, developing, powering desktop, web & small server applications, and for redistribution by ISVs. The SQL Server 2014 Express release includes the full version of SQL Server 2014 Management Studio instead of SQL Server 2014 Management Studio Express.
http://msdn.microsoft.com/en-us/library/dn434042.aspx

Starting T-SQL

SQL Server Management Studio is not installed by default. If Management Studio is unavailable, install it by running Setup. Management Studio is not available with SQL Server Express. Management Studio Express is available as a free download from the Microsoft Download Center, but has a different user interface than is described in this tutorial.
http://msdn.microsoft.com/en-us/library/ms166996.aspx

To open SQL Server Management Studio

    • On the Start menu, point to All Programs, point to Microsoft SQL Server 2014, and then click SQL Server Management Studio.
    • In the Connect to Server dialog box, verify the default settings, and then click Connect. To connect, the Server name box must contain the name of the computer where SQL Server is installed. If the Database Engine is a named instance, the Server name box should also contain the instance name in the format <computer_name>\<instance_name>.

Hello World!

Retrieves rows from the database and enables the selection of one or many rows or columns from one or many tables in SQL Server. The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:
[ WITH <common_table_expression>]
SELECT select_list [ INTO new_table ]
[ FROM table_source ] [ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
The UNION, EXCEPT and INTERSECT operators can be used between queries to combine or compare their results into one result set.
http://technet.microsoft.com/en-us/library/ms189499.aspx

  1. Open SQL Server Management Studio
  2. Click File, point to New, and then select Query with Current Connection
  3. Type SELECT 'Hello World!'
  4. Execute the script by pressing [F5]
"Hello World!"

Variables

Variables are declared in the body of a batch or procedure with the DECLARE statement and are assigned values by using either a SET or SELECT statement. Cursor variables can be declared with this statement and used with other cursor-related statements. After declaration, all variables are initialized as NULL, unless a value is provided as part of the declaration.
http://msdn.microsoft.com/en-us/library/ms188927.aspx

DECLARE @message AS nvarchar(max)
SET @message = 'Hello World!'
SELECT @message
"Hello World!"

Functions

Like functions in programming languages, SQL Server user-defined functions are routines that accept parameters, perform an action, such as a complex calculation, and return the result of that action as a value. The return value can either be a single scalar value or a result set.
http://msdn.microsoft.com/en-us/library/ms191007.aspx

BEGIN…END
Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed. BEGIN and END are control-of-flow language keywords.
http://msdn.microsoft.com/en-us/library/ms190487.aspx

GO
Signals the end of a batch of Transact-SQL statements to the SQL Server utilities.
http://msdn.microsoft.com/en-us/library/ms188037.aspx

BEGIN
	DECLARE @message AS nvarchar(max)
	SET @message = 'Hello World!'
	SELECT @message
END
GO

Attaching a Sample Database

RELEASE NOTES
About this release
This release consolidates AdventureWorksDW databases for SQL Server 2012, 2008R2 and 2008 versions to one page. Each zip file contains an mdf database file and an ldf log file. This should make it easier to find and download AdventureWorksDW databases since all OLAP versions are on one page.
http://msftdbprodsamples.codeplex.com/releases/view/93587

An AdventureWorksDW database can be installed by attaching the database, or using the CREATE DATABASE statement.
To attach an AdventureWorks database

  1. Download a database for your SQL Server version.
  2. Unzip the database (mdf) file and log (ldf) file.
  3. From Microsoft SQL Server Management Studio, connect to a SQL Server instance.
  4. Right click Databases.
  5. Click Attach.
  6. Click the Add button.
  7. Locate the AdventureWorksDW database mdf file. For instance, AdventureWorksDW2012_Data.mdf.
  8. Click the OK button on the Locate Database Files dialog window.
  9. Click the OK button on the Attach Databases dialog window to attach the database.

SAMPLE DATABASE statement
From SQL Server Management Studio, execute the following T-SQL:
Example T-SQL

-- Select ALL records from the AdventureWorks0212 database in table Sales.Store
SELECT * FROM [AdventureWorks2012].[Sales].[Store]

Further Reading

Documentation for SQL Server 2014 Tools and Add-in Components

  • The table lists SQL Server tools and add-ins, and provides links to additional documentation in the MSDN Library.

W3Schools SQL Tutorial

  • SQL tutorial will teach you how to use SQL to access and manipulate data in: MySQL, SQL Server, Access, Oracle, Sybase, DB2, and other database systems.

Python Primer

About Python

Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on Windows 2000 and later.
https://docs.python.org/3/faq/general.html#what-is-python

Download Python

All Python releases are Open Source. Historically, most, but not all, Python releases have also been GPL-compatible. The Licenses page details GPL-compatibility and Terms and Conditions.
https://www.python.org/downloads/

To Chose between Python V2 or V3 visit this page. IronPython, Python with .Net, runs V2 for example.

Starting Python

IDLE is the Python IDE built with the tkinter GUI toolkit.
IDLE has the following features:

  • coded in 100% pure Python, using the tkinter GUI toolkit
  • cross-platform: works on Windows, Unix, and Mac OS X
  • multi-window text editor with multiple undo, Python colorizing, smart indent, call tips, and many other features
  • Python shell window (a.k.a. interactive interpreter)
  • debugger (not complete, but you can set breakpoints, view and step)

https://docs.python.org/3/library/idle.html

Do the following:

    • Click Start, point to All Programs, point to Python 3.4, and then click IDLE (Python GUI).

Hello World!

  1. Open IDLE
  2. Click File and then click New File
  3. Type print('Hello World!')
    1. Note: In Python V2 it would be print 'Hello World!'
  4. Execute the code by pressing [F5]
"Hello World!"

Variables

The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.
Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.
Some operations are supported by several object types; in particular, practically all objects can be compared, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function). The latter function is implicitly used when an object is written by the print() function.
https://docs.python.org/3/library/stdtypes.html

message = 'Hello World!'
print(message)
"Hello World!"

Functions

The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.
https://docs.python.org/3/tutorial/controlflow.html#defining-functions

message = 'Hello World!'
def WriteMessage():
    print(message)
# Call the function
WriteMessage()
"Hello World!"

Passing Variables to Functions

Previously, message was accessible because its scope was Global. You can pass variables and values to functions by appending those values to the function call. Also, your function must expect a value. In this example, we pass a string into the function that we declare as message.

def WriteMessage(message):
    print(message)
# Call the function
WriteMessage('Hello World!')
"Hello World!"

Error Handling

The try statement specifies exception handlers and/or cleanup code for a group of statements.
The except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed.
If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses.
https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

import sys, os

def WriteMessage(message):
    print(message)

try:
    # Call the function
    WriteMessage('Hello World!')
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)
finally:
    # Write message
    WriteMessage('Finally...')
"Hello World!"

Further Reading

Python Documentation

  • The Python Software Foundation’s documenation for Python.

Python Wiki

  • The Python Wiki’s collection of programming guides, documentation, books, tools, and community.

Related

Pytools

  • PTVS is a free, open source plugin that turns Visual Studio into a Python IDE.

PowerShell Primer

About PowerShell

Windows PowerShell® is a task-based command-line shell and scripting language designed especially for system administration. Built on the .NET Framework, Windows PowerShell helps IT professionals and power users control and automate the administration of the Windows operating system and applications that run on Windows.
http://technet.microsoft.com/en-us/library/bb978526.aspx

Download PowerShell

Windows Management Framework 4.0 includes updates to Windows PowerShell, Windows PowerShell ISE, Windows PowerShell Web Services (Management OData IIS Extension), Windows Remote Management (WinRM), Windows Management Instrumentation (WMI), the Server Manager WMI provider, and a new feature for 4.0, Windows PowerShell Desired State Configuration (DSC).
http://www.microsoft.com/en-us/download/details.aspx?id=40855

Starting PowerShell

The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages. You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint.
http://technet.microsoft.com/en-us/library/dd315244.aspx

Do one of the following:

    • Click Start, point to All Programs, point to Windows PowerShell V2, and then click Windows PowerShell ISE.
    • In the Windows PowerShell console Cmd.exe, or in the Run box, type, powershell_ise.exe.

Hello World!

The Write-Host cmdlet enables you to write messages to the Windows PowerShell console.
http://technet.microsoft.com/en-us/library/ee177031.aspx

  1. Open PowerShell ISE
  2. Click File and then click New
  3. Type Write-Host "Hello World!"
  4. Execute the script by pressing [F5]
"Hello World!"

Variables

When you write a script, particularly a system administration script, you rarely get to hard-code in all your values ahead of time; instead, you typically need to retrieve information, store that information in a variable or two, and then display the values of those variable.
http://technet.microsoft.com/en-us/library/ee692790.aspx

PowerShell is influenced by Unix shells and Perl so variables are prefixed with a $sigil.

$message = 'Hello World!'
Write-Host $message
"Hello World!"

Functions

A function is a list of Windows PowerShell statements that has a name that you assign. When you run a function, you type the function name. The statements in the list run as if you had typed them at the command prompt.
http://technet.microsoft.com/en-us/library/hh847829.aspx

Windows PowerShell uses a verb-noun pair for the names of cmdlets and for their derived Microsoft .NET Framework classes. For example, the Get-Command cmdlet provided by Windows PowerShell is used to retrieve all the commands that are registered in Windows PowerShell. The verb part of the name identifies the action that the cmdlet performs. The noun part of the name identifies the entity on which the action is performed.
http://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx

$message = "Hello World!"
function Write-Message()
{
    Write-Host $message
}
# Call the function
Write-Message
"Hello World!"

Passing Variables to Functions

Previously, $message was accessible because its scope was Global. You can pass variables and values to functions by appending those values to the function call. Also, your function must expect a value. In this example, we pass a string into the function that we declare as $message.

function Write-Message([string]$message)
{
    Write-Host $message
}
# Call the function
Write-Message "Hello World!"
"Hello World!"

Error Handling

Use Try, Catch, and Finally blocks to respond to or handle terminating errors in scripts. The Trap statement can also be used to handle terminating errors in scripts. For more information, see about_Trap.
http://technet.microsoft.com/en-us/library/hh847793.aspx

function Write-Message([string]$message)
{
    Write-Host $message
}

try
{
    # Call the function
    Write-Message "Hello World!"
}
catch [Exception]
{
    # Write exception to host
    Write-Host ("==> Caught Exception: {0}" -f $_.Exception.Message)
}
finally
{
    # Pause the script so that the result can be viewed before the console closes
    Pause
}
"Hello World!"

NOTE: The exception string is built using composite formatting:
{0} is the argument.
-f is the format operator.
$_ is this (keyword).

Further Reading

Scripting with Windows PowerShell

  • Microsoft TechNet’s complete guide to PowerShell.
  • Contains documentation, guides, and related links.

An A-Z Index of Windows PowerShell 2.0 commands

  • SS64 has compiled an alphabetical list of PS v2 commands.

Related Reading

How to Run PowerShell Commands on Remote Computers

  • Hot-To Geek’s guide to enable PowerShell Remoting

Calling PowerShell Function from Command Line

  • StackOverflow Q&A