Wednesday, December 18, 2019

Portable Objects in PowerShell with CLIXML

As a Database Administrator, it’s essential to keep track of the systems you manage as they change over time. There are several ways to do that, and I’ve found PowerShell objects especially useful.

This article covers creating portable objects which allow you to collect data on one server and copy that data to another server. Then you can continue to work with the objects. It’s especially useful when you want to limit your work on the source server to minimize resource usage, or you want to collect data from many servers in one place and process that data as a group.

Before there was PowerShell . . .

In my early days as a DBA, I worked on Sybase SQL Server (version 4.2, for those asking) on Unix servers. To collect information from those servers, I’d use Korn shell scripts to iterate through the servers and gather the information I needed. Here’s a sample script I used over 20 years ago to collect logins across all my servers:

. /software/admin/bin/SAPSSWD
SA_PASSWORD=`echo $SAPSSWD`
SHORTNAME=`echo $1 | cut -c1-4`
echo "Using short name of .${SHORTNAME}"
echo "select name,@@servername,'#' from syslogins where name like '%${SHORTNAME}%'" > /tmp/t
echo "go" >> /tmp/t
isql -Usa -Scli42a -i/tmp/t -P${SA_PASSWORD} | tee /tmp/t.out
isql -Usa -Scli42b -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
isql -Usa -Scli44a -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
isql -Usa -Scli45a -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
isql -Usa -Scli46a -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
isql -Usa -Scli47a -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
isql -Usa -Scli47b -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
isql -Usa -Scli48a -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
isql -Usa -Scli48b -i/tmp/t -P${SA_PASSWORD} | tee -a /tmp/t.out
DATASERVERS=`cat /tmp/t.out | sed -e s/name//g | sed -e s/-//g | sed -e /.row./d`
rm /tmp/t.out   
rm /tmp/t

(Yes, I’d do things differently today, with the security concerns we have in today’s world.)

When I ran this script, which selects login and server name (and a #) from each of the nine servers, it returns a list in the DATASERVERS variable of all the logins and which server they are defined. (This is Korn shell on a Unix box running against Sybase servers.) In the script, isql does what you now do using sqlcmd. cli4xx is the name of the server, and the results are tee’d to both the console and to the t.out file. I used this script to find all the servers where a given login (SHORTNAME) was defined so that I could update or remove it.

The thing I’d like to point out is the line where I build the DATASERVERS variable. I’m taking the results from the queries that have been directed to the t.out file in the /tmp directory. Then I use the sed (stream editor) utility to filter out any occurrences of the string ‘name’, then the string ‘-‘, and then deleting any line that has the string ‘row’ prefixed or suffixed by 0 or more characters. (Try the command in SSMS with results to text, and the edits will make more sense.)

This method is the standard in Unix environments for piping the results of one utility into another. You have to ensure that the results of one are correctly formatted to be usable in the next utility in the pipeline.

PowerShell and .NET Objects

One of the first features I found amazing in PowerShell is the use of .NET objects for everything. What’s especially great is that I don’t have to use sed (or grep, or awk) to do all the formatting I as I did in Unix environments to get the same power when writing my scripts.

For example, if I want to see what’s running on my server, I run the Get-Process command:

If I want to pull back a specific process name, I can pipe the results to the where-object cmdlet (aliased as just ‘where’), testing each member of the results to see if the Name property is equal to ‘sqlservr’.

Get-Process | where {$_.Name -eq 'sqlservr'}

If I want to see the top five most memory-consuming processes, I can sort (sort-object) on the WorkingSet (WS) column in descending order, and then select (select-object) the first five.

Get-Process | sort workingset -desc | select -first 5

There’s no text manipulation here, as I had to do using the Korn shell 20 years ago. Objects contain properties, and I can select just the properties I want or can filter by specific (or wildcarded) values, as I need. I can discover what properties are available for a specific cmdlet by piping the command to Get-Member.

Get-Process | Get-Member

As you can see, there are a lot of properties available in this object. Each object is defined by its type (in this case it’s a System.Diagnostics.Process object), and Get-Member returns the properties and methods for the object, as well as other MemberTypes.

As a consultant, I work with systems for multiple clients, and the work I do often requires that I be disconnected from the client systems. This is where PowerShell’s special CLIXML (Common Language Infrastructure XML) type comes into play.

PowerShell Object Serialization

When you move data from one computer to another in PowerShell, it does so by serializing the object – exporting to another form – into XML, usually. There are a lot of options for exporting data out of PowerShell. There’s Export-Csv, and there’s a number of options using the ConvertTo verb, including ConvertTo-Html, ConvertTo-Json, and ConvertTo-Xml. Each of these cmdlets serialize the data in the objects in different ways, but most of them strip out most of the object features. Let’s look at an example.

$sqlps = Get-Process | where {$_.Name -eq 'sqlservr'}
$sqlps | ConvertTo-Xml -as String | Set-Content -path c:\work\SQLProcessXML.xml

The results show a standard XML file with values for the individual properties.

<?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object Type="System.Diagnostics.Process">
    <Property Name="Name" Type="System.String">sqlservr</Property>
    <Property Name="SI" Type="System.Int32">0</Property>
    <Property Name="Handles" Type="System.Int32">929</Property>
    <Property Name="VM" Type="System.Int64">7689175040</Property>
    <Property Name="WS" Type="System.Int64">418717696</Property>
    <Property Name="PM" Type="System.Int64">482795520</Property>
    <Property Name="NPM" Type="System.Int64">115392</Property>
    <Property Name="Path" Type="System.String">C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe</Property>
    <Property Name="Company" Type="System.String">Microsoft Corporation</Property>
    <Property Name="CPU" Type="System.Double">27.03125</Property>
    <Property Name="FileVersion" Type="System.String">2017.0140.1000.169 ((SQLServer).170822-2340)</Property>
    <Property Name="ProductVersion" Type="System.String">14.0.1000.169</Property>
    <Property Name="Description" Type="System.String">SQL Server Windows NT - 64 Bit</Property>
…

CLIXML is structured differently, however, and contains a lot more information. You can also use the Export-Clixml command to export it.

$sqlps | Export-Clixml c:\work\SQLProcessCLIXML.xml

The output file looks like this:

<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Diagnostics.Process</T>
      <T>System.ComponentModel.Component</T>
      <T>System.MarshalByRefObject</T>
      <T>System.Object</T>
    </TN>
    <ToString>System.Diagnostics.Process (sqlservr)</ToString>
    <Props>
      <I32 N="BasePriority">8</I32>
      <B N="HasExited">false</B>
      <Obj N="Handle" RefId="1">
        <TN RefId="1">
          <T>System.IntPtr</T>
          <T>System.ValueType</T>
          <T>System.Object</T>
        </TN>
        <ToString>7088</ToString>
      </Obj>
      <Obj N="SafeHandle" RefId="2">
        <TN RefId="2">
          <T>Microsoft.Win32.SafeHandles.SafeProcessHandle</T>
          <T>Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid</T>
          <T>System.Runtime.InteropServices.SafeHandle</T>
          <T>System.Runtime.ConstrainedExecution.CriticalFinalizerObject</T>
          <T>System.Object</T>
        </TN>
        <ToString>Microsoft.Win32.SafeHandles.SafeProcessHandle</ToString>
        <Props>
          <B N="IsInvalid">false</B>
          <B N="IsClosed">false</B>
        </Props>
      </Obj>
      <I32 N="HandleCount">929</I32>
      <I32 N="Id">2808</I32>
      <S N="MachineName">.</S>
      <Obj N="MainWindowHandle" RefId="3">
        <TNRef RefId="1" />
        <ToString>0</ToString>
      </Obj>
      <S N="MainWindowTitle"></S>
      <Obj N="MainModule" RefId="4">
        <TN RefId="3">
          <T>System.Diagnostics.ProcessModule</T>
          <T>System.ComponentModel.Component</T>
          <T>System.MarshalByRefObject</T>
          <T>System.Object</T>
        </TN>
        <ToString>System.Diagnostics.ProcessModule (sqlservr.exe)</ToString>
        <Props>
          <S N="ModuleName">sqlservr.exe</S>
          <S N="FileName">C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe</S>
          <S N="BaseAddress">140702702632960</S>
          <I32 N="ModuleMemorySize">516096</I32>
          <S N="EntryPointAddress">140702702798896</S>
          <S N="FileVersionInfo">File:             C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe_x000D__x000A_InternalName:     SQLSERVR_x000D__x000A_OriginalFilename: SQLSERVR.EXE_x000D__x000A_FileVersion:      2017.0140.1000.169 ((SQLServer).170822-2340)_x000D__x000A_FileDescription:  SQL Server Windows NT - 64 Bit_x000D__x000A_Product:          Microsoft SQL Server_x000D__x000A_ProductVersion:   14.0.1000.169_x000D__x000A_Debug:            False_x000D__x000A_Patched:          False_x000D__x000A_PreRelease:       False_x000D__x000A_PrivateBuild:     False_x000D__x000A_SpecialBuild:     False_x000D__x000A_Language:         English (United States)_x000D__x000A_</S>
          <Nil N="Site" />
          <Nil N="Container" />
        </Props>
        <MS>
          <I32 N="Size">504</I32>
          <S N="Company">Microsoft Corporation</S>
          <S N="FileVersion">2017.0140.1000.169 ((SQLServer).170822-2340)</S>
          <S N="ProductVersion">14.0.1000.169</S>
          <S N="Description">SQL Server Windows NT - 64 Bit</S>
…

As you can see, things are quite different.

The standard XML file contains the information in the object, but much like you’d do when you put it into a report. The CLIXML file, on the other hand, contains the entire object structure, including the object definitions of the properties within the objects. Because of this, you can import the CLIXML file, using the Import-Clixml cmdlet, and have the complete object in the variable you assign the import to.

As an example, you can use the Get-Content cmdlet to import the data into an XML variable.

[xml]$ps = Get-Content c:\work\SQLProcessXML.xml

You can then navigate down to the Property elements to retrieve the values. In PowerShell, it’s fairly easy to navigate an XML object by using dots (‘.’) to separate the XML elements.

$ps.Objects.Object.Property

On the other hand, with CLIXML, you can use the Import-Clixml cmdlet to retrieve the original object.

$cli = Import-Clixml e:\work\SQLProcessCLIXML.xml

Then, the full depth of the original object is returned.

$cli 
$cli | Get-Member

As you can see, the CLIXML object retains the original object type. Note that it’s been deserialized, so you have all the data in the original object. You can access the object members as you normally would, but the original methods and nested properties are excluded. The important thing to consider is that if you’re planning on using the data in another application, you probably want to use a format appropriate to that application, like JSON, XML, CSV, etc. If, on the other hand, if you’re going to use that data in another PowerShell session, then CLIXML is the format you should use.

Object Portability

The benefit I principally get from CLIXML is the ability to capture data at client systems, then port those objects to my own systems for later analysis.

One of the first things I do when starting with a new client is gather performance metrics using the Get-Counter cmdlet. I’ve got a short script that I use to define the servers I need counters from, the counters I want, and it then uses Invoke-Command to execute the script locally on each of the defined servers.

$srvrs = 'WS16SQL1','WS16SQL2','WS16SQL3'
Invoke-Command -ComputerName $srvrs -ScriptBlock {
        $srv = $env:COMPUTERNAME
        $iname = 'sqlserver'
        $dtstr = (get-date).ToString('yyyyMddHHmm')
        $counters = @(
            "\Processor(_Total)\% Processor Time",
            "\Memory\Available MBytes",
            "\Paging File(_Total)\% Usage",
            "\PhysicalDisk(_Total)\Avg. Disk sec/Read",
            "\PhysicalDisk(_Total)\Avg. Disk sec/Write",
            "\System\Processor Queue Length",
            "\$($iname):Access Methods\Forwarded Records/sec",
            "\$($iname):Access Methods\Page Splits/sec",
            "\$($iname):Buffer Manager\Buffer cache hit ratio",
            "\$($iname):Buffer Manager\Page life expectancy",
            "\$($iname):Databases(_Total)\Log Growths",
            "\$($iname):General Statistics\Processes blocked",
            "\$($iname):SQL Statistics\Batch Requests/sec",
            "\$($iname):SQL Statistics\SQL Compilations/sec",
            "\$($iname):SQL Statistics\SQL Re-Compilations/sec"
        )
        
        # Get performance counter data
        $ctr = Get-Counter -ComputerName $srv -Counter $counters -SampleInterval 60 -MaxSamples 1440
        $ctr | Export-Clixml "c:\\work\\$($srv)_counters_$($dtstr).xml"
}

I load the names of the servers into the $srvrs variable and use that to tell Invoke-Command which servers to run the script on. In PowerShell, any executable set of commands, within a pair of braces ({ and }), is called a ScriptBlock. The commands within the ScriptBlock get the local computer name and set the date string to the current date and time. It then defines the individual counters to be gathered into a hash table called $counters. The $iname variable contains the instance name to be used in the counters. In most environments, companies use the default instance, and so I’ve coded this making that assumption.

Once the variables needed for Get-Counter are set, I call Get-Counter, specifying a sample interval of 60 seconds and a maximum number of samples at 1440. Essentially, I’m gathering the counters once a minute, for 24 hours. (If you want to try out the script in a shorter time period, just modify those values.) When the Get-Counter cmdlet completes 24 hours later, it assigns the collection of counter values to the $ctr variable. It then pipes that variable to Export-Clixml, which writes the collection to a file in the local work directory with the server name and the date and time the process started in the file name.

I collect these files and copy them locally to my own machine where I have a second script that imports the CLIXML files and loads the counter values into a database table. I then have reports that read that data and produce reports that show the counters in both graphical and tabular values.

Without installing anything at my client site, I’m able to gather important performance metrics and build a performance baseline against which I can evaluate any changes I make going forward. If you would like to use these reports yourself, you can download the schema and report definitions here.

SQL Power Doc

Kendal Van Dyke (@sqldba) wrote a set of PowerShell modules and scripts that, in two separate steps, collect Windows and SQL Server configuration data, and convert that data into three separate spreadsheets. One contains all the Windows operating system and server configuration data. A second workbook contains SQL Server instance, database, and Agent configuration data. A third workbook provides an analysis of the configuration data and provides an assessment of that configuration against known best practices, with links to the Microsoft documentation describing the best practice descriptions.

There’s a single download zip file you can get from GitHub and, in that file, are the modules, the scripts you need to run, and text documents explaining how to run the scripts. (Note that running the scripts requires local admin rights on each of the servers from which data is collected. This is due to the breadth of information the scripts collect, which use a combination of Windows Management Instrumentation (WMI) and SQL Server Server Management Objects (SMO) to gather its data.)

The first step of the process uses one of the “Get” scripts. I almost always use the Get-SqlServerInventoryToClixml.ps1 script. This script then searches the computers provided in the -ComputerName argument and gathers the configuration data. If I have the necessary privileges, I run this from a workstation in my client environment, and if I don’t, I ask someone who does to run it for me. It doesn’t change anything; it just collects data.

The file it produces is a CLIXML file, compressed using gzip, thus the gz extension.

I then copy the gz file to my local machine and run the second script – Convert-SqlServerInventoryClixmlToExcel.ps1, which produces the spreadsheets I described earlier.

Caveat

I’ve run into many cases where an object I’m working with is not serializable. For example, using the brilliant scripts provided by the dbatools project, I’ve found that some of the objects I’ve retrieved are serializable (Get-DbaComputerSystem, Get-DbaDiskSpace) where others are not (Get-DbaLogin). When they are not, PowerShell throws an error.

Experiment with serialization and the CLIXML file format. You’ll find the right combination of commands that will meet your requirements.

Summary

Over the years, I’ve been successful using scripting to automate the processes of administering databases. PowerShell has been a tremendous step forward from when I started with Korn shell. It’s also important to localize your work, so you don’t use resources on server systems unnecessarily. It’s in this case, where the power of CLIXML comes in handy, to move objects from the servers that have other work to do to your local machine, where you can continue the work without using the server resources.

 

The post Portable Objects in PowerShell with CLIXML appeared first on Simple Talk.



from Simple Talk https://ift.tt/2sFyMXG
via

Friday, December 13, 2019

Debugging in Unity

Inevitably, when you are developing a game, you will need to debug your Unity project, and you’ll do this multiple times throughout development. Sometimes you may run into an issue that isn’t easily found by replaying the game numerous times. There are times where you’ll need tools to uncover a project’s issues faster. Fortunately, Unity has provided some helpful debugging tools to make squashing bugs a little easier. In addition, Visual Studio tools can be used alongside Unity for access to more debugging options.

A project showcasing many of the debugging options available to you is soon to follow. Many of the tools are some variation of displaying a message in the debug console. These messages can be plain text, warnings, or errors. There are also commands that draw debug lines in Unity’s Scene window as well as code that distinguishes if an exe of your game is a development build or not. All this will be utilized in a scene consisting of two capsules and some text.

Project Creation

Upon opening Unity Hub, create a new project, as shown in Figure 1.

Figure 1: Creating a new project

A new window opens that displays all the project templates available. All the debugging tools shown here will work in any project, but the example to follow will be in 3D. Give your project a name and location and click the Create button shown in Figure 2.

Figure 2: Project creation

Once the project has been created, you’ll need to create two capsule objects. This can be done in the Hierarchy menu by clicking Create 3D Object Capsule, as shown in Figure 3.

Figure 3: Creating capsule objects

Set the position of the two capsules to whatever you’d like, so long as the positions are noticeably different. The figure below put both capsules’ Z position at -5.6 and Y position at 0. The first capsule’s X position is at -2.9, and the second capsule’s X position is at 3.1. Figure 4 shows how the scene will look.

Figure 4: The current scene

Some text will be displayed whenever the game runs from a development build. If it is not a development build, then the text will be hidden. To create this text, use the same create menu as before and navigate to 3D Object-3D Text. Position the text wherever you wish and set the message by going to the Text Mesh component under the Inspector window and editing Text. Figure 5 shows some example text.

Figure 5: Entering text

Once everything is in place, create a new script by going into the Assets window, right-clicking, and selecting Create C# Script as shown in Figure 6.

Figure 6: Creating a C# script

Give the script a name, then double click it to open Visual Studio.

Debug Messages and More

One of the most common ways to debug a game is to print messages to the debug console. The messages can contain any info you wish such as a string, integer value, boolean, or a combination of variable types. The most basic of these messages is Debug.Log, which prints a message of your choice. In the example below, Debug.Log should be placed within the Start method, and it will print “Let the games begin” to Unity’s debug console.

Debug.Log("Let the games begin");

The next two functions are similar to Debug.Log. In fact, they all begin with “Debug.Log.” These two commands are Debug.LogError and Debug.LogWarning. You may be able to tell what these commands do. LogError will log a custom error message to Unity’s console, while LogWarning prints a warning message to the console. Once again, these two functions will be put to use in the Start method. An error message will print “I am error” to the console and a warning message saying “I’m warning you.”

Debug.LogError(“I am error”);

Debug.LogWarning(“I’m warning you!”);

Debugging means more than printing messages; you can tell Unity to pause the game by using Debug.Break. This is useful whenever you need to pause the game at specific points but can’t manually pause it yourself. For example, if you want to make sure a projectile fired from an object is moving at the correct trajectory, you may wish to use Debug.Break to pause the game so you can analyze that trajectory and make any necessary corrections in code. Add the code under the Debug.Log statements.

Debug.Break();

Going back to message printing, you have Debug.Assert. Like Debug.LogError, it also prints an error message. But there is one key difference – it only prints if an assigned boolean is false. In this example, a boolean has been declared and is used in Debug.Assert. The boolean was given the attribute SerializeField to make it visible in the Unity editor. This was done so you can set the boolean to true or false and see how Debug.Assert works more clearly.

Debug.Assert(assertionBool, 
    "I print to the screen if asssertionBool is false.");

Finally, there’s Debug.LogException, which prints out whatever exception message is given to Unity’s console. There aren’t any real surprises here, as it behaves like printing an exception message would in any other C# project. In scenario taking place in the Start function, the program tried to convert a string into an integer, which of course won’t work if the string has anything but numbers. The exception is caught and displayed in the Unity console. Note: you’ll need to add using System; above the class for this code to work correctly.

try
        {
            // something that will throw an exception
            string someString = "This is some string";
            Debug.Log("Breakpoint activate");
            int someNum = Convert.ToInt32(someString);
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);        
        }

Once finished, the Start method should appear like the one in Figure 7.

Figure 7: The complete Start method.

Other functions print messages to the console, including LogFormat and LogWarningFormat, but they’re very similar to the functions already shown. These are the functions you’ll want to know when it comes to printing information to the Unity console. If you want to see how all these work now, save the code and return to the Unity editor. Attach the script to any object you wish. The example in Figure 8 attaches the script to the Main Camera object.

Figure 8: Attaching MyScript to an object

Set the Assertion Bool value to whatever you wish, then run the project. Nothing will happen in-game of course, but you can view the debug messages either by clicking on the console text in the lower right of the editor or by navigating to Window General Console shown in Figure 9. You may also notice that the project is currently paused, signified by the state of the pause button near the top of the editor. This is thanks to Debug.Break doing its work.

Figure 9: Unity debug console

Drawing Lines

The next two debug functions, Debug.DrawLine and Debug.DrawRay, draw lines in Unity’s Scene window while the game is running. What’s the difference? DrawLine, as the name implies, draws a line from point A to point B. In this project, the line will be drawn starting at one capsule object and ending at the other. DrawRay, on the other hand, draws out a ray using a starting point and extending out a certain direction. You would typically use DrawRay to better visualize where a raycast (an invisible line) is going. For instance, in many shooters, it’s not a physical bullet that comes out of the gun but instead, a raycast being fired. Developers will use little tricks, such as the appearance of a muzzle flash. This will look like an actual bullet leaves the gun, but there’s usually no object being shot out. From there, the game determines if you hit something based on if that raycast collided with an object.

Before you can try out anything, you’ll first need a couple of new variables. Below the declaration for assertionBool, enter the following:

[SerializeField]
private Transform firstTransform;
[SerializeField]
private Transform secondTransform;

These variables will hold the Transform data of the two capsule objects. Transforms include the position data of an object, which is what you’ll need for DrawLine. In the Update function you’ll write:

Debug.DrawLine(firstTransform.position, 
    secondTransform.position, Color.red);

As you can see, the line begins at firstTransform‘s, or the first capsule’s, position and goes to the second capsule’s position. The color of the line has also been set to red, though it can be whatever color you’d like. In addition, you can add a fourth parameter specifying how long you wish the line to be drawn in seconds. In this case, the code is in the Update method and doesn’t require a time since it will be drawn every frame. The same thing can be done in Debug.DrawRay.

As mentioned before, Unity will need a direction for drawing the ray. This will be done by creating a new variable of type Vector3 and defining the direction and, while you’re at it, how long the line will be. Once done, you can input that into DrawRay along with the starting position and a color. The example sets the starting position to the second capsule. It can be whatever object you wish including the camera object itself if you give it this as input for its first parameter.

Vector3 forward = 
    transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(secondTransform.position, forward, Color.blue);

Figure 10 shows how the script looks with the new code (the Start method is collapsed in the below figure):

Figure 10: Debug.DrawLine and Debug.DrawRay

You can see how this looks in the editor by saving your code. Then back in Unity, make sure to fill in the First Transform and Second Transform fields in the MyScript component you attached to your object. In this example shown in Figure 11, the script was attached to Main Camera.

Figure 11: Setting First Transform and Second Transform

Run the project and have a look at the Scene window. You should see two lines: one red line between the two capsule objects, and a blue line coming from your object of choice, as shown in Figure 12.

Figure 12: The debug line and ray as seen in the Scene window

Development Builds

There’s not much to be said about development builds as it relates to code, but there is one useful debug boolean that should be highlighted. Remember that text object created during the project creation phase? The text can appear or disappear based on if the build is a development build.

First, add a new variable declaration. This variable will be connected to the text object in Unity once the code is modified.

[SerializeField]
private GameObject devBuildText;

To get this to work, Debug.isDebugBuild will be put to use. Go back to the Start method and add the following code at the beginning:

if (Debug.isDebugBuild)

devBuildText.SetActive(true);

else

devBuildText.SetActive(false);

To properly test this will require running the game as an exe file. But there’s an issue. Once you run the project, there’s no way to close out of the game except via Alt-Tab or Task Manager. In the Update method, a simple if statement will be added. This will check if the escape key has been pressed at any point during the game’s runtime. If it has, then it will close the application. The code can be placed anywhere in the Update method and looks like this:

if (Input.GetKeyDown(KeyCode.Escape))
        Application.Quit();

This is all that’s needed to disable an object based on if the exe is a development build or not. To see this in practice will require saving the code and returning to the Unity editor once more. In the MyScript component, you’ll need to fill the Dev Build Text field by dragging your text object from the Hierarchy window into it, as shown in Figure 13.

Figure 13: Setting Dev Build Text

Running the project from the editor will cause the text to remain visible. To better see the effect in action, go to the project’s build settings by navigating to File Build Settings. The following window appears, as shown in Figure 14.

Figure 14: Build settings

You should see a checkbox for Development Build. Leave that unchecked if you want the text object to vanish in the exe. All you need to do is click the Build and Run button, choose a location, then let Unity build an exe. Once it’s finished, the exe should run automatically, and you’ll notice the text is nowhere to be seen.

Ticking the box to mark this as a development build will, of course, reveal the text, but there are also a few helpful items you get as a result. For starters, you ordinarily can only use Unity’s Profiler, a tool that tracks performance statistics in your game such as frame rate and CPU usage, in the editor. By marking this exe as a development build, you’ll be able to use the Profiler on your exe. There’s even an option in the build settings shown in Figure 15 that automatically connects the Profiler for you upon build completion. Of course, the Unity editor will still need to be open to do any of this.

Figure 15: Activating Development Build and Autoconnect Profiler

But wait, there’s still more! You may have noticed after running your development build exe that some error messages showed up in the exe. They’re the same ones you created yourself earlier. Development builds also have a console that can print out messages, but unfortunately, the functionality appears to be limited to just error messages. Still, this can be useful as you playtest your game. If you click the error message, more information appears including the exact script and line of code the error occurred in.

Debugging Using Breakpoints in Visual Studio

You also have the option to use breakpoints in Visual Studio for Unity project debugging. This would be similar to the Debug.Break function introduced earlier, but you get the perks of using Visual Studio’s breakpoints such as seeing current variable values. To add a breakpoint, select a line of code and press F9. In Figure 16, the Debug.Break function in the Start method has been commented out to test out Visual Studio breakpoints. Debug.Log was added to the try method, and the breakpoint was set on the line with Debug.Log.

Figure 16: Setting a breakpoint

To see this in action, save the code, then select Attach to Unity in the top menu, as shown in Figure 17.

Figure 17: Attaching Visual Studio to Unity

Once Visual Studio is ready, run the project in the Unity editor. If done correctly, Unity will immediately pause the game at the point the breakpoint is reached. This would be the time to have a look at Visual Studio and gather whatever information you’re looking for in the Autos window shown in Figure 18. When you’re done looking, hit the Continue button in Visual Studio to resume the game in Unity.

Figure 18: Checking out the values of variables in the Visual Studio debugger

Breakpoints can also be used with development builds, though there are a few extra steps to do so. First, you must make sure that you have Script Debugging selected. Doing so will cause a new option to appear. This option is Wait for Managed Debugger, and you’ll want that selected too, as shown in Figure 19.

Figure 19: Activating Script Debugging and Wait For Managed Debugger

Build and run the project like before. Before launching the game, Unity should allow you a moment to attach whatever debugger you wish. Once it gives you the prompt, head over to Visual Studio, then navigate to Debug Attach Unity Debugger, as shown in Figure 20.

Figure 20: Navigating to Attach Unity Debugger

A window appears asking you to select the Unity instance. You should see two options in this window shown in Figure 21. Select the option of type Player and click the OK button. This is you telling Visual Studio you wish to attach the debugger to the exe.

Figure 21: Selecting the Unity instance

Once again, wait for Visual Studio to be ready. When ready, you can select OK in Unity’s pop up box to start the game. Like last time, the game pauses at the breakpoint allowing you to see information like variable values. Since the breakpoint occurs in the Start method, you may be presented with a blank screen in the exe because Unity was not quite finished rendering everything out. Press the Continue button in Visual Studio to resume the project as usual.

Conclusion

As nice as it would be for all code to work flawlessly the first time, the fact is that dream rarely becomes a reality. Debugging is an inevitability in the life of a programmer. For the Unity developer, there are a handful of tools provided to make bug-squashing easier, ranging from simple custom messages to visualizing raycasts. Utilizing development builds can also make development easier, even coming with its own console so you can see any errors that pop up. You can also get crafty with development builds by creating custom tools that appear in development builds. These allow you to do whatever tasks you wish, such as skipping levels or tinkering with variables in real-time.

 

The post Debugging in Unity appeared first on Simple Talk.



from Simple Talk https://ift.tt/34jiy3B
via

ASP.NET Core with GitOps: Orchestrating Your Containers with Kubernetes

The series so far:

In the previous tutorial, you learned how to write and deploy your Infrastructure as Code using AWS CloudFormation. This allowed you to launch several EC2 instances that run your Docker image.

The next step towards automatization is to have an orchestration system for your containers for deploying, scaling and managing them. For this series, you will be using AWS EKS (Elastic Kubernetes Service), but there are alternatives – even inside AWS- which will be presented during this article.

Understanding Kubernetes and EKS

Kubernetes is an open-source system designed by Google; as stated on their website, it is a “portable, extensible, open-source platform for managing containerized workloads and services.” This means that you can use Kubernetes to deploy and handle your containers (in this case, Docker containers) automatically.

Kubernetes works by having multiple nodes – basically, machines, whether they are virtual or physical – which handle running the pods – a container, or perhaps a group of containers. In this series, a node will be represented by an EC2 instance, while each pod will be a Docker container.

While bringing a lot of benefits to your infrastructure, running a Kubernetes cluster proves to be quite difficult. One of the services that can ease your work is Amazon’s Elastic Kubernetes Service. It has alternatives on the other big cloud providers – Google Kubernetes Engine (GKE) and Azure Kubernetes Service (AKS). Choosing between them can depend on multiple factors, such as the current knowledge of your team, costs, and where your infrastructure is currently deployed. If you are already running a large number of servers, databases, and VMs on Azure, for example, switching to Google Cloud Platform just because of Kubernetes would not make much sense.

The biggest drawback of EKS is probably its cost – as opposed to its competitors, which provide free services. It requires $0.2/hour/cluster, in addition to the costs of running the rest of your infrastructure, such as your EC2 instances and your databases.

What About Elastic Container Service (ECS)?

As mentioned earlier, there are alternatives to Kubernetes even inside AWS. ECS is an orchestration service that is native to AWS, provides better integration with other services from the platform, and is free of charge. You still pay for your instances and other services, but the orchestration capabilities are provided for free.

You can find many comparisons between ECS and EKS, and the choice should be made based on your organization’s needs; you will find ECS to be easier to learn, and you might find that it solves your problems, so you don’t have to dive into Kubernetes. One of the GitHub Actions most popular pipelines is deploying your application to ECS, so you can have your container orchestration ready faster than you think.

However, since this series is aiming to teach GitOps principles and practices, rather than platform-native solutions, the rest of the tutorial will focus on EKS.

Installing kubectl

Kubectl is a command-line interface (CLI) used for working with Kubernetes clusters. Even though you are using EKS, you need Kubectl to configure the cluster, set the image that is going to be deployed, and debug the process.

To install kubectl on your system, you can check out the guide on the Kubernetes website. After you finish the installation, verify the major and minor versions by running kubectl version. These are important when creating the EKS cluster, as the cluster and kubectl version must be within one minor version of each other.

You might also get the following message after checking the version: “The connection to the server localhost:8080 was refused – did you specify the right host or port?”. This happens because kubectl defaults the connection to localhost:8080; you will get to change this later when connecting to the EKS cluster.

Creating an EKS Cluster

The first step towards having Kubernetes deploy and manage your containers is to create an EKS cluster in your Infrastructure as Code. Most of the other resources will remain unchanged: you still need an Auto Scaling Group, a Launch Configuration and their underlying infrastructure. The main change will happen in the Launch Configuration, where instead of running your Docker container manually, you will ask the EKS cluster to handle that for you.

The EKS cluster requires an IAM role to be able to manage the resources. You can choose to add the role in your IaC file, but since it’s more of a “static” resource, creating it manually from the AWS console is not wrong. To do this, search for IAM in the Find services box:

Select IAM, likely the first option. Then, from the left side of the screen, choose Roles and click the Create role button:

From the list of services that appears, search for EKS and click it, then click the Next: Permissions button.

You should see the policies that are attached to the role:

Continue to click the Next buttons until you are asked to choose a role name. Pick something that will be intuitive, such as eks-console-access, and click the Create role button.

You can then search for the role in the table that opens up by using the name you just picked, and you should see a page with the details of your role:

Copy the Role ARN value for later use. It will be needed when creating the EKS cluster.

One more policy should be attached to the role. Click Attach policies and search for the AmazonSSMFullAccess policy. It will be needed for pulling the image ID later. Select the policy and click Attach policy.

Now the three policies should be attached to the role.

It is now time to open your infrastructure.yaml file (from the previous article) and make the necessary modifications. You will create the EKS and get the nodes to attach to it. As in the previous tutorial, this can be a process of trial and error, but a good starting point is AWS’s template. It is very generic, but it is the best way to learn precisely what is needed, and you can adapt it to your own needs.

To understand the changes that are going to be made to the infrastructure file, you need to understand resource tagging. Generally, tags allow you to manage and search for your resources more efficiently. In the case of EKS, however, tags are necessary for your nodes to attach to the cluster.

Because you are creating an EKS cluster, change the Description in the top of the file:

Description: Creating an EKS cluster with multiple EC2 instances.

Next, a new security group needs to be created for the EKS. This is done to be able to manage the cluster independently from the nodes, as well as to avoid future circular dependencies in the infrastructure:

EksSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref VPC
      GroupDescription: Default security group for EKS.
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 1025
          ToPort: 65535
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
      SecurityGroupEgress:
        - IpProtocol: tcp
          FromPort: 1025
          ToPort: 65535
          CidrIp: 0.0.0.0/0

This security group allows communication on port 443, as well as any port between 1025 and 65535. You can find more information about which ports are necessary and recommended for your cluster in the AWS documentation.

Next, you can create the EKS cluster. This requires the ARN of the role you created earlier, the security group, as well as a list of subnets where your worker nodes will be hosted. The latest version supported on AWS right now is 1.14, but you can use any of the other supported versions.

EKS:
    Type: AWS::EKS::Cluster
    Properties:
      Version: '1.14'
      RoleArn: arn:aws:iam::358599436160:role/eks-console-access
      ResourcesVpcConfig:
        SecurityGroupIds:
          - !Ref EksSecurityGroup
        SubnetIds:
          - !Ref Subnet1
          - !Ref Subnet2

Now that you have the cluster ready, you can tag the related resources so that the nodes can attach to the cluster. The security group used by the nodes (MainSecurityGroup, in this case), as well as the Auto Scaling Group and the instances inside it, need a tag with the key kubernetes.io/cluster/{eks-id} and the value owned. Replace the MainSecurityGroup from your file with this code:

MainSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Security group for the API instances.
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - IpProtocol: "-1"
          FromPort: 0
          ToPort: 65535
          CidrIp: 0.0.0.0/0
      SecurityGroupEgress:
        - IpProtocol: "-1"
          FromPort: 0
          ToPort: 65535
          CidrIp: 0.0.0.0/0
      Tags:
        - Key: 
              !Sub 
                  - "kubernetes.io/cluster/${EksId}"
                  - EksId: !Ref EKS
          Value: 'owned'

Replace the AutoScalingGroup in your file with this code:

AutoScalingGroup:
    DependsOn: EKS
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      VPCZoneIdentifier:
       - !Ref Subnet1
       - !Ref Subnet2
      LaunchConfigurationName:
        Ref: LaunchConfiguration
      DesiredCapacity: 3
      MinSize: 2
      MaxSize: 4
      Tags:
        - Key: 
              !Sub 
                  - "kubernetes.io/cluster/${EksId}"
                  - EksId: !Ref EKS
          Value: 'owned'
          PropagateAtLaunch: 'true'

For the Auto Scaling Group, you can also see the PropagateAtLaunch property being set to the tag. This will ensure that the tag will also be applied to any instance inside the group.

Although you already have an IAM role for the cluster, creating another one for the launch configuration and for accessing the cluster through the console can be a good idea. This role would need other policies than the one you created earlier:

InstanceRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ec2.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy
        - arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy
        - arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly
  InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
        - !Ref InstanceRole

The image ID is also changed, as AWS provides a list of image IDs that are required to be used when working with EKS. You can find the list here. You should use it to find the right ID for your situation, as they are divided by Kubernetes versions, as well as AWS regions. Be sure to match the version of kubectl that you installed and the version specified in the EKS section of the file. After finding the right image for you, it is possible to pull the latest version from AWS automatically. To do this, create a parameter (add to the Parameter section) in the file with the image ID name as the default value:

AmiId:
    Description: The AMI to use for the EKS nodes.
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/eks/optimized-ami/1.14/amazon-linux-2/recommended/image_id'

The final step is to link the cluster to the Launch Configuration; you need to specify the AMI and execute a Shell script instead of running the Docker container. Replace the LaunchConfigration section with this code:

LaunchConfiguration:
    DependsOn: EKS
    Type: AWS::AutoScaling::LaunchConfiguration
    Properties:
      IamInstanceProfile: !Ref InstanceProfile
      UserData:
        Fn::Base64: 
          !Sub 
            - |
                #!/bin/bash
                set -o xtrace
                /etc/eks/bootstrap.sh ${EksId}
                /opt/aws/bin/cfn-signal --exit-code $? \
                        --stack  ${AWS::StackName} \
                        --resource AutoScalingGroup  \
                        --region ${AWS::Region}
            - EksId: !Ref EKS
       ImageId: !Ref AmiId
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeSize: 8
            VolumeType: gp2
            DeleteOnTermination: true
      SecurityGroups:
      - Ref: MainSecurityGroup
      InstanceType: t2.micro

The bootstrap.sh script is used to add the instances into the cluster; the next script, /opt/aws/bin/cfn-signal will signal when the instances are created and ready to be used.

Once you finish this, you can delete the LoadBalancer, Listener, ListenerRule and TargetGroup sections from your file. They no longer provide any value: the EKS cluster will take the role of a load balancer. You can find the final version of the file here.

Because of the IAM role that you added to the stack, you need to let CloudFormation know that it is allowed to create such resources. To do this, add the --capabilities flag to your update or create command from the previous article to create the stack. Run this in the command or terminal window replacing the Docker <username> and <password>:

aws cloudformation create-stack --stack-name dotnet-docker --template-body file://infrastructure/infrastructure.yaml --parameters ParameterKey=DockerUsername,ParameterValue=<username> ParameterKey=DockerPassword,ParameterValue=<password> --capabilities CAPABILITY_IAM

Updating or recreating the stack will take some time at this point, because of the EKS. Once it is finished, you should see the three instances being created in your EC2 dashboard. However, none of them is running any application at this point, as you have not told the cluster what image to run.

Managing the Containers

In your AWS Console, go to the CloudFormation dashboard, select your stack and go to the Resources tab. You need two values from here – the ARN of the role that was created from the file, and the ID of the cluster.

For the ARN, search for the InstanceRole resource and click the link in the Physical ID column:

The summary page for the role will open, and you can copy the ARN from there:

 

For the cluster, just search for the EKS resource and copy the Physical ID column:

Before being able to interact with the cluster from EKS, you need to create a file that will tell AWS you are allowed to do so. Create a file called aws-auth-cm.yaml and paste the following content into it. Replace <ARN> with the value copied earlier.

apiVersion: v1
kind: ConfigMap
metadata:
  name: aws-auth
  namespace: kube-system
data:
  mapRoles: |
    - rolearn: <ARN>
      username: system:node:
      groups:
        - system:bootstrappers
        - system:nodes

The first step for interacting with the cluster via CLI is to run the following command, to tell AWS which cluster you are going to work with. Replace <region> with the AWS region you are working in, such as eu-central-1, and <eks-id> with the physical ID of your cluster.

aws eks --region <region> update-kubeconfig --name <eks-id>

You should receive an output similar to this:

If you receive an error like “Invalid choice: ‘eks’”, it is because your awscli version is outdated. Update your package and make sure your version is at least 1.15.32.

Next, you will need to apply the AWS authentication file to the cluster, so you have access to its resources:

kubectl apply -f aws-auth-cm.yaml

This should output:

Note that the path to the aws executable must be in your PATH variable for this command to work if you are running Windows.

From this point, you can start managing your cluster. A good start is to check if the nodes were created correctly. If you followed the tutorial, you should see three nodes after running the command:

kubectl get nodes

It should output something similar to this:

If you cannot see any nodes, several things could have gone wrong:

  • Run sudo kubectl version and make sure the client and server versions are the same (or one minor version apart);
  • Make sure you are pulling the correct AMI for the version you are using;
  • Check the aws-auth-cm.yaml file and make sure you have the correct role ARN; also check the indentation of the file, because you will not receive any errors;

The next step is to create a deployment file. The deployment file tells the cluster what image to deploy, how many containers it should create, and what method to use when updating them. The file creates a rolling update, meaning that new pods are added gradually, as old ones are destroyed, allowing your application to continue serving requests. You can read more about all the options here.

The file looks like the code below. Be sure to replace <username> with your own Docker username:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: dotnet-api
  labels:
    app: dotnet-api
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      app: dotnet-api
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: dotnet-api
    spec:
      containers:
      - image: docker.io/<username>/dotnet-api
        imagePullPolicy: Always
        name: dotnet-api
        ports:
        - containerPort: 80
          protocol: TCP

If you wish to deploy another image, you will change the -image line. Make sure the containerPort is also the one on which you expect your application to use.

Save this to a file called cluster-deployment.yaml and apply it to the cluster:

kubectl apply -f cluster-deployment.yaml

This command will create three pods, one running on each node. You can check this by running either one of the following commands:e

kubectl get deployments
kubectl get pods

You are now ready to expose your application through a cluster load balancer:

kubectl expose deployment dotnet-api --type=LoadBalancer --port=80 --target-port=80

To get the load balancer’s IP, run:

kubectl get svc

Copy the External-IP value from the output:

It might take a couple of minutes for the application to deploy, but you can append the standard/api/test to the external IP to test that everything is working as intended. If the app is running, you’ll see this message:

If at any point, you need to update the application served by the cluster, you can update the Docker image and then run the following command replacing your Docker <username>:

kubectl set image deployment/dotnet-api dotnet-api=docker.io/<username>/dotnet-api:latest

Debugging the Cluster

Working with Kubernetes can be a tedious process, with many things going wrong along the way.

One of the most common problems is the nodes not attaching to the cluster. This is most likely due to the wrong configuration in the infrastructure: check the launch configuration’s AMI, the Kubernetes version from EKS, and make sure the resources are correctly tagged.

If the nodes and pods are created, but the application is not running, the describe command can reveal a lot of information. You can run it on the pods, as well as the svc, to discover any issues, such as scheduling, or the image not being pulled:

kubectl describe pods
kubectl describe svc

Cleaning Up

Before deleting the stack, you need to delete the deployment and the svc. Since the deployment creates a load balancer, it will prevent you from deleting the stack as long as it exists. The command order is:

kubectl delete deployment dotnet-api
kubectl delete svc dotnet-api   
aws cloudformation delete-stack --stack-name dotnet-docker

What is Next?

With Kubernetes, you are now able to easily manage a large number of containers with just a few commands. You can scale up or down, update the application that is being served, and diagnose any problems that appear along the way.

The next and final tutorial will teach you how to automate this process by using a CI/CD pipeline: any new commit to the master branch will result in the Docker image being pushed to the remote hub, and then updated in your cluster.

 

 

The post ASP.NET Core with GitOps: Orchestrating Your Containers with Kubernetes appeared first on Simple Talk.



from Simple Talk https://ift.tt/38xKBzv
via

Wednesday, December 11, 2019

Service Pack – Fix Missing MSI issue

You know what it’s like, you are running a service pack on SQL Server and 99.9% of the time it all runs smoothly but that odd 0.1% of the time when it doesn’t is usually in the middle of the night with no one around to call on.

Well to spare you some pain I’ve discovered a really cool utility to help mitigate risk.

I was recently doing a service pack, I’d run it on the entire test estate and half of the Production estate, I’d used Pinal Dave’s really useful AG check list and been really overcautious, I’d finished integrity checks on all databases, I’d backed everything up and even had a snapshot of the server completed.

When I clicked on the service pack I got the error  “missing MSI” sorry I don’t have the screen dump or the full error message because at the time of trying to fix it I did’t think to take a copy ☹

I understand the prime reason for this happening is that the installer files had been removed.

Anyway after a lot of bingling I discovered this blog from Microsoft which gives you the link to download a really cool little utility that can help you fix the missing MSIs, or at least help you identify them.

I would strongly recommend running the utility while you are preparing for service patching so that you can resolve any issues rather than having to deal with it in the middle of the night.

When you run the utility it will ask you for the installer drive, by default this is c:\windows\installer it may return something like this:

Hopefully it will return an empty table, however if it does return data we know what to do to fix it.

You can see that in the screen dump I’ve fixed two missing msi’s and failed to fix 3.  However this does give us really useful information.  We know what the msi we are missing relates to and the number SQL Server has given to it.  SQL Server randomizes the CachedMSIMsp so you can’t just find that one.

Instead what you have to do to fix this is search out the package name, sql_is.msi, by the time I’d got to this point  I’d downloaded the version of SQL Server I was working with and tried a repair which had failed.  Search for the package name, so looking at the first one it’s sql_is.msi, copy it to c:\windows\installer and rename it to, in our case, 83717132.msi, repeat this for all missing msi’s and then you should be able to re-run the service pack successfully.

The post Service Pack – Fix Missing MSI issue appeared first on Simple Talk.



from Simple Talk https://ift.tt/2Pd2uvP
via

Wednesday, December 4, 2019

Distractions at Work

Many jobs in technology, especially those that involve writing code, take concentration and focus. It’s often called being “in the zone.” For me, it feels like I’m inside a bubble where time goes at a different pace than the rest of the world. In fact, the rest of the world seems to disappear when I’m in the zone…until I’m interrupted, that is.

Studies have been done to measure how long it takes developers to become productive again after being interrupted, and 15 to 20 minutes is usually reported. One study from the University of California Irvine found it took an average of 23 minutes for managers to get back on task, but they became accustomed to interruptions and worked harder to make it up.

Distractions can come in many forms. In today’s world of open offices, it’s hard to concentrate. It’s difficult to tune out all the conversations. The worst is when a co-worker puts a conference call on speakerphone. Why do that? The idea behind these environments is that workers will collaborate more, but there is nowhere to hide when you need to be left alone to get some work done. These floorplans encourage chit-chat and “drive-by” requests, and some developers resort to headphones to tune out the noise.

Even sanctioned work tools like company email can be distractions when you are writing code or solving a performance problem. Author Tim Ferriss recommends spending just one hour per week on Monday morning to read email in his book The 4-Hour Workweek. In my opinion, that schedule is not going to work for most people in any IT role or those who don’t want to miss messages from managers. Maybe it makes sense to limit checking work email messages to twice a day if one hour a week is not frequent enough.

Many companies are limiting emails and instead are using tools like Slack to communicate among teams. The idea is that, if you are at your desk, you will immediately see the message and be expected to respond. In his article about how to eliminate distractions from Slack, author Joe Casabona says “Slack makes it very easy for people to take you out of the moment – it’s the virtual knock on the door and, ‘hey you have a minute?’” (And don’t get me started about the number of channels I’m expected to watch!)

Disruptions decrease productivity and ultimately hurt the bottom line. Maybe one day, someone will design the perfect office, and companies will implement “no interruption time” policies. Until then, it’s back to the headphones.

Commentary Competition

Enjoyed the topic? Have a relevant anecdote? Disagree with the author? Leave your two cents on this post in the comments below, and our favourite response will win a $50 Amazon gift card. The competition closes two weeks from the date of publication, and the winner will be announced in the next Simple Talk newsletter.

The post Distractions at Work appeared first on Simple Talk.



from Simple Talk https://ift.tt/2qjC3Ld
via

Building a Countdown Timer with PowerShell

When one thinks of PowerShell, one thinks of it as a scripting language. Generally, this is true. While you can write a script that prompts for input and provides output, usually there are no real GUI elements involved, and a cursory glance at the list of PowerShell cmdlets reinforces this idea.

However, it is possible to create a GUI with PowerShell; it just takes a bit more work. Furthermore, once one understands how to do this, it can lead to far more powerful scripts in the future.

A Simple Timer

As with some of my projects, this one started as sort of a challenge to myself. I wanted to create a script that created a form on the screen, and I wanted it to do something. I decided to start with something simple, a form that counted down the time and then closed. (NOTE: The examples in this article work in classic PowerShell but not PowerShell Core since Core is multiplatform.)

Save the following script as Countdown Timer_1.ps1.

$delay = 10
$Counter_Form = New-Object System.Windows.Forms.Form
$Counter_Form.Text = "Countdown Timer!"
$Counter_Form.Width = 450
$Counter_Form.Height = 200
$Counter_Label = New-Object System.Windows.Forms.Label
$Counter_Label.AutoSize = $true 
$Counter_Form.Controls.Add($Counter_Label)
while ($delay -ge 0)
{
  $Counter_Form.Show()
  $Counter_Label.Text = "Seconds Remaining: $($delay)"
  start-sleep 1
  $delay -= 1
}
$Counter_Form.Close()

The loop should be self-evident. It starts with the selected $delay value and counts down, sleeping for 1 second at a time until it hits 0. Note that due to how PowerShell works, the one-second delay in start-sleep has some slop to it. You should not use this script to launch a space shuttle, but for everyday use it’s fine.

The interesting part of this script is not the loop; it’s the New-Object System.Windows.Forms.Form line. To anyone who has worked with C# or VB.Net or any other .Net managed code, this should look familiar. You are simply calling into the .Net Framework to create a form. This innocuous statement will mean huge ramifications later.

Once you have your form object, you can start to assign some properties, in this case, the title (in the .text) property and height and width.

Finally, you need to put a new object on this form, a label. Once you’ve done that, you simply loop through for the length of your $delay and the form will count down. You should see a screen that looks like this. (Note that the scripts in this article were tested on Dell and Lenovo laptops, an old HP desktop, and an Azure VM but no guarantee that the forms will look the same on all machines. You may have to tweak some of the numbers in the scripts to see the same results.)

It’s not pretty, but it gets the job done. To fix some of the more obvious problems and create something a bit nicer looking, save the following script as Coutndown Timer_2.ps1.

$delay = 10
$Counter_Form = New-Object System.Windows.Forms.Form
$Counter_Form.Text = "Countdown Timer!"
$Counter_Form.Width = 450
$Counter_Form.Height = 200
$Counter_Label = New-Object System.Windows.Forms.Label
$Counter_Label.AutoSize = $true
$Counter_Label.ForeColor = "Green"
$normalfont = New-Object System.Drawing.Font("Times New Roman",14)
$Counter_Label.Font = $normalfont
$Counter_Label.Left = 20
$Counter_Label.Top = 20
$Counter_Form.Controls.Add($Counter_Label)
while ($delay -ge 0)
{
  $Counter_Form.Show()
  $Counter_Label.Text = "Seconds Remaining: $($delay)"
  if ($delay -lt 5)
  { 
     $Counter_Label.ForeColor = "Red"
     $fontsize = 20-$delay
     $warningfont = New-Object System.Drawing.Font("Times New Roman",$fontsize,[System.Drawing.FontStyle]([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Underline))
     $Counter_Label.Font = $warningfont
  } 
 start-sleep 1
 $delay -= 1
}
$Counter_Form.Close()

You should get something like this when you run the script:

 

You now have a countdown timer that you can control the label position, font size, style and color which is all very useful. In this case, I took advantage of the ability to move the label down a bit, make the font larger and to change color and size as the countdown approached 0.

Adding Functionality

The previous example is a simple timer, but to make it useful, you will need to add some controls. Again, you can take advantage of the fact that classic PowerShell can make calls into the Windows forms dll.

In addition, you will take advantage of the ability to pass parameters as you start to make this a fully functional application. This time, you will add a new label, a text edit box and OK and Cancel buttons. Combined, all these should give you a fully functional countdown timer.

The following script combines all of the above:

param([int]$delay=3, [string]$EventLabel = "This is a test")
#Setup initial form
$Counter_Form = New-Object System.Windows.Forms.Form
$Counter_Form.Text = "Countdown Timer!"
$Counter_Form.Width = 450
$Counter_Form.Height = 200
$Counter_Form.WindowState = "Normal"
#Setup our Normal font
$normalfont = New-Object System.Drawing.Font("Times New Roman",14)
#Setup initial label
$Counter_Label = New-Object System.Windows.Forms.Label
$Counter_Label.AutoSize = $true
$Counter_Label.ForeColor = "Green"
$Counter_Label.Font = $normalfont
$Counter_Label.Left = 20
$Counter_Label.Top = 50
#setup input areas
$Counter_GetDelay_Label = New-Object System.Windows.Forms.Label
$Counter_GetDelay_Label.AutoSize = $true
$Counter_GetDelay_Label.Text = "Enter Delay:"
$Counter_GetDelay_Label.Left = 10
$Counter_GetDelay_Label.Top = 8
$Counter_Form.Controls.Add($Counter_GetDelay_Label)
$Counter_GetDelay_TextBox = New-Object System.Windows.Forms.TextBox
$Counter_GetDelay_TextBox.AutoSize = $true 
$Counter_GetDelay_TextBox.Text = $delay
$Counter_GetDelay_TextBox.Left = $Counter_GetDelay_Label.Left + $Counter_GetDelay_Label.Width + 10
$Counter_GetDelay_TextBox.Top = 5
$Counter_Form.Controls.Add($Counter_GetDelay_TextBox)
$Counter_Event_Label = New-Object System.Windows.Forms.Label
$Counter_Event_Label.AutoSize = $true 
$Counter_Event_Label.Text = $EventLabel
$Counter_Event_Label.Location = '20,100' # note we're using a different method to position the text here.
$Counter_Event_Label.Font = $normalfont
#Setup and handle the OK button
$Counter_OKButton = New-Object System.Windows.Forms.Button
$Counter_OKButton.AutoSize = $true 
$Counter_OKButton.Text = "Ok"
$Counter_OKButton.Left = 80
$Counter_OKButton.Top = 40
$Counter_OKButton.Add_Click({
  $delay=$Counter_GetDelay_TextBox.Text
  $Counter_Form.Controls.Remove($Counter_GetDelay_Label)
  $Counter_Form.Controls.Remove($Counter_GetDelay_TextBox)
  $Counter_Form.Controls.Remove($Counter_OKButton)
  $Counter_Form.Controls.Remove($Counter_CancelButton)
  $Counter_Form.Controls.Add($Counter_Label)
  $Counter_Form.Controls.Add($Counter_Event_Label)
  while ($delay -gt 0)
  {
      $Counter_Label.Text = "Seconds Remaining: $($delay)"
      if ($delay -lt 5)
      { 
          $Counter_Label.ForeColor = "Red"
          $fontsize = 20-$delay
          $warningfont = New-Object System.Drawing.Font("Times New Roman",$fontsize,[System.Drawing.FontStyle]([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Underline))
          $Counter_Label.Font = $warningfont
      } 
      start-sleep 1
      $delay -= 1
   }
   $Counter_Form.Close()
  }
)
$Counter_Form.Controls.Add($Counter_OKButton)
#Setup and handle the cancel button
$Counter_CancelButton = New-Object System.Windows.Forms.Button
$Counter_CancelButton.AutoSize = $true 
$Counter_CancelButton.Text = "Cancel"
$Counter_CancelButton.Left = $Counter_OKButton.Left + $Counter_OKButton.Width + 10
$Counter_CancelButton.Top = 40
$Counter_CancelButton.Add_Click({$counter_form.Close() })
$Counter_Form.Controls.Add($Counter_CancelButton)
#Setup and handle keyboard Enter/Escape
$Counter_Form.AcceptButton=$Counter_OKButton
$Counter_Form.CancelButton=$Counter_CancelButton
#Finally, we show the dialog
$Counter_Form.ShowDialog() | Out-Null #absorbs cancel message at end. This occurs for reasons outside scope of this article

You can call it from the command line and pass the parameter –EventLabel “Now we can really rock!”

& '.\Countdown Timer_3.ps1' -EventLabel "Now we can really rock!"

When you run it, you will get something like this:

Clicking the Ok button will result in the following:

I will leave it to you as the reader to figure out how to add the possibility of editing the passed in EventLabel parameter within the dialog box.

Controlling the Form Position

When you run this multiple times, you will notice that the position of the dialog box itself changes each time. The next version will fix this. In fact, in the next step, you will make this a fairly functional countdown timer that fills up most of the screen and looks professional.

param([int]$delay=3, [string]$EventLabel = "This is a test")
#Get monitor resolution of primary monitor
$monitordetails = [System.Windows.Forms.SystemInformation]::PrimaryMonitorSize
$monitorheight = $monitordetails.Height
$monitorwidth = $monitordetails.Width
#Setup initial form
$Counter_Form = New-Object System.Windows.Forms.Form
$Counter_Form.Text = "Countdown Timer!"
$Counter_Form.Height = $monitorheight * .80
$Counter_Form.Width = $monitorwidth * .80
$Counter_Form.WindowState = "Normal"
$Counter_Form.Top = $monitorheight *.10
$Counter_Form.Left = $monitorwidth *.10
$Counter_Form.StartPosition = "manual"     # this ensures we can control where on the screen the form appears
#Setup our Normal font
$normalfont = New-Object System.Drawing.Font("Times New Roman",28)   # We will use this size and type of font throughout
#Setup initial label
$Counter_Label = New-Object System.Windows.Forms.Label
$Counter_Label.ForeColor = "Green"
$Counter_Label.Font = $normalfont
#setup input areas
# This will let prompt for the delay if it wasn't passed in on the command line.
$Counter_GetDelay_Label = New-Object System.Windows.Forms.Label
$Counter_GetDelay_Label.AutoSize = $true
$Counter_GetDelay_Label.Text = "Enter Delay:"
$Counter_GetDelay_Label.Left = 10
$Counter_GetDelay_Label.Top = 8
$Counter_Form.Controls.Add($Counter_GetDelay_Label)
$Counter_GetDelay_TextBox = New-Object System.Windows.Forms.TextBox
$Counter_GetDelay_TextBox.AutoSize = $true 
$Counter_GetDelay_TextBox.Text = $delay
$Counter_GetDelay_TextBox.Left = $Counter_GetDelay_Label.Left + $Counter_GetDelay_Label.Width + 10
$Counter_GetDelay_TextBox.Top = 5
$Counter_Form.Controls.Add($Counter_GetDelay_TextBox)
$EventLabel_Size= [System.Windows.Forms.TextRenderer]::MeasureText($EventLabel, $normalfont)
$Counter_Event_Label = New-Object System.Windows.Forms.Label
$Counter_Event_Label.Width = $EventLabel_Size.Width+6  # Apparently despite giving it the string, we need a little extra room.
$Counter_Event_Label.Height= $EventLabel_Size.Height
$Counter_Event_Label.Text = $EventLabel
$Counter_Event_Label.Left = ($Counter_Form.Width/2)-($EventLabel_Size.Width/2)
$Counter_Event_Label.Top = ($Counter_Form.Height/2)-($EventLabel_Size.Height/2)
$Counter_Event_Label.Font = $normalfont
#Setup and handle the OK button
$Counter_OKButton = New-Object System.Windows.Forms.Button
$Counter_OKButton.AutoSize = $true 
$Counter_OKButton.Text = "Ok"
$Counter_OKButton.Left = 80
$Counter_OKButton.Top = 40
$Counter_OKButton.Add_Click({
   # Get our delay the user entered.
   $delay=$Counter_GetDelay_TextBox.Text
  
   # Get rid of the controls we don't need any more.
   $Counter_Form.Controls.Remove($Counter_GetDelay_Label)
   $Counter_Form.Controls.Remove($Counter_GetDelay_TextBox)
   $Counter_Form.Controls.Remove($Counter_OKButton)
   $Counter_Form.Controls.Remove($Counter_CancelButton)
   # Now add the labels we want.
   $Counter_Form.Controls.Add($Counter_Label)
   $Counter_Form.Controls.Add($Counter_Event_Label)
   while ($delay -gt 0)
   {
      $Counter_Label.Text = "Seconds Remaining: $($delay)"
      $Counter_LabelSize= [System.Windows.Forms.TextRenderer]::MeasureText($Counter_Label.Text , $normalfont) # we need this so we can figure where to put the countdown labeled, centered.
      $Counter_Label.Font = $normalfont
      $Counter_Label.AutoSize = $true
      $Counter_Label.Left = ($Counter_Form.Width/2)-($Counter_LabelSize.Width/2)  # We want it centered.
      $Counter_Label.Top = $Counter_Form.Height * .3 # We want it near the bottom of the screen.
      if ($delay -le 5)  # Now things are getting close, let's change the color and make it bolder and underline it
      { 
          $Counter_Label.ForeColor = "Red"
          $warningfont = New-Object System.Drawing.Font("Times New Roman",28,[System.Drawing.FontStyle]([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Underline))
          $Counter_Label.Font = $warningfont
          $Counter_LabelSize= [System.Windows.Forms.TextRenderer]::MeasureText($Counter_Label.Text , $warningfont)
          $Counter_Label.Width = $Counter_LabelSize.Width + 10
          $Counter_Label.Left = ($Counter_Form.Width/2)-($Counter_LabelSize.Width/2)
      } 
      start-sleep 1
      $delay -= 1
  }
  $Counter_Form.Close()
})
$Counter_Form.Controls.Add($Counter_OKButton)
#Setup and handle the cancel button
$Counter_CancelButton = New-Object System.Windows.Forms.Button
$Counter_CancelButton.AutoSize = $true
$Counter_CancelButton.Text = "Cancel"
$Counter_CancelButton.Left = $Counter_OKButton.Left + $Counter_OKButton.Width + 10
$Counter_CancelButton.Top = 40
$Counter_CancelButton.Add_Click({$counter_form.Close() })
$Counter_Form.Controls.Add($Counter_CancelButton)
#Setup and handle keyboard Enter/Escape
$Counter_Form.AcceptButton=$Counter_OKButton
$Counter_Form.CancelButton=$Counter_CancelButton
#Finally, we show the dialog
$Counter_Form.ShowDialog() | Out-Null #absorbs cancel message at end. This occurs for reasons outside scope of this article

You’ve now created a fully functional countdown timer that will automatically scale to the size of the screen and allow you to configure how long it runs for and what primary message it displays. Future improvements might be to allow the option of having a background graphic and being able to more easily abort the timer in the middle of it running.

Conclusion

Hopefully, now you can see that through the power of PowerShell, in combination with the built-in .Net capabilities, you can create full-fledged applications that can interact with the user, prompting them for input and also providing them with output. In fact, pretty much anything you can do in C# or VB.Net can be done in a very similar fashion in PowerShell without needing to write a full-blown application. That said, writing an application like this using PowerShell ISE can be tedious. For example, it took me a while to get the positioning correct, mostly due to a few typos here and there (for example, using width when I meant height and vice versa). There are plug-ins for Visual Studio and other stand-alone IDEs that can make this task easier. But I wanted to demonstrate the power of PowerShell out of the box without any further add-ons or tools.

All scripts in this article are also available at: https://github.com/stridergdm/SimpleTalk_PowerShell-Scripts

 

The post Building a Countdown Timer with PowerShell appeared first on Simple Talk.



from Simple Talk https://ift.tt/34WAW3r
via