The Kirkland Coder

Friday, April 10, 2015

File Name Validation

In a continuing effort to keep track of my coding notes, here is another function I wrote that I use a lot. It uses "Path" to get a list of invalid characters to check against.

 using System;
using System.IO;
using System.Text.RegularExpressions;

namespace DemoSolution
{
    class Program
    {
        static void Main(string[] args)
        {
            string badFileName = @"This!has*INVALID:characters.txt";
            string goodFileName = @"This-has_INVALID.characters.txt";

            Console.WriteLine("badFileName = {0}", badFileName.IsValidFileName());
            // OUTPUT: badFileName = False

            Console.WriteLine("goodFileName = {0}", goodFileName.IsValidFileName());
            // OUTPUT: goodFileName = True
        }
    }

    public static class MyExtensions
    {
        /// 
        /// Checks the string to see if any invalid characters exist for a file name.
        /// 
        /// 
        /// 
        ///     Returns "True" if the file name has no invalid
        ///     characters, else it returns "False".
        /// 
        /// 
        /// string fileName = "Valid_File-Name.txt";
        /// 
        public static bool IsValidFileName(this string FileName)
        {
            // Create the RegEx pattern to match
            Regex BadPathCharacters = new Regex(
                "[" + Regex.Escape(String.Join("", Path.GetInvalidFileNameChars()))
                + "]");

            // See if any of the characters are a match. 
            if (BadPathCharacters.IsMatch(FileName))
            {
                return false;
            }
            return true;
        }
    }
}

Tuesday, December 9, 2014

When I need to allow only Net Bios characters I use this function. It can be used to make sure a user enters a proper server name.

/// 
/// Will allow text entered into a textbox to be Net Bios safe.
/// If the key pressed is not good, it is fake handled. 
/// 
/// Can be called from XAML like so:
///     
///     
/// NOTE: PreviewTextInput is WPF Device safe as compared to checking the keyboard.
/// 
/// 
/// 
public static void NetBiosAllowedTextOnly(object sender, TextCompositionEventArgs e)
{
    // Get the entered text
    string TheText = e.Text;

    ////////////////////////////////////////////////////////////////////////////
    //    NetBIOS computer names cannot contain the following characters:     //
    //    • backslash (\)           • slash mark (/)                          //
    //    • colon (:)               • asterisk (*)                            //
    //    • question mark (?)       • quotation mark (")                      //
    //    • less than sign (<)      • greater than sign (>)                   //
    //    • vertical bar (|)                                                  //
    ////////////////////////////////////////////////////////////////////////////
    if (-1 < TheText.IndexOfAny(new char[] { '\\', '/', ':', '*', '?', '\"', '<', '>', '|' }))
    {
        // Not allowed character so pretend it was handled.
        e.Handled = true;
    }
    else
    {
        // Allowed character, let it be handled regularly.
        e.Handled = false;
    }
}

Thursday, September 26, 2013

MD5 Hash function

Had to get the MD5 Hash on some files and needed a light weight script. So here it is:

function Get-Md5Hash
{
    <#
        .SYNOPSIS
        This function returns the Md5 Hash for a given file.
 
        .DESCRIPTION
        This function returns the Md5 Hash for a given file.
        You can Pipe in files or just use one at a time.
 

        .EXAMPLE
        PS C:\> $ReturnedHash = Get-Md5Hash "c:\test\MyFile.txt"
 
        .EXAMPLE
        PS C:\> @("C:\TEST\TestFile1.txt","C:\TEST\TestFile2.txt","C:\TEST\TestFile3.txt") | Get-Md5Hash
 
        .INPUTS
        A file name/location.
 
        .OUTPUTS
        The Md5 Hash of the given file is returned.
 
        .NOTES
        Function Name: Get-Md5Hash
        Original Author: Norman Skinner (normans)
        Original Created on: 09/26/2013
        Version: 1.0.0.0
 
        HISTORY:
        ===========#==============#======================================
        Date       | User         | Description
        -----------+--------------+--------------------------------------
        09/26/2013 | normans      | Created script
        -----------+--------------+--------------------------------------
                   |              | 
        -----------+--------------+--------------------------------------
                   |              | 
        -----------+--------------+--------------------------------------
    #>
 
    param
    (
        [parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string]
        # This the file for getting the Md5 hash.
        $File
    )
    PROCESS
    {
        $MD5object = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
        $Md5Hash   = [System.BitConverter]::ToString($MD5object.ComputeHash([System.IO.File]::ReadAllBytes($File)))
        return $Md5Hash
    }
}

Friday, November 30, 2012

Merge hash tables like shuffling cards.

Continuing on my work with hash tables, I have created a the new function “Merge-Hashtables”. For my own convenience I added two switches. One to remove NULLs and another to force the use of the second hash tables values when two keys match.

I have added a few examples to the function help on the use and output examples.

function Merge-Hashtables
{
    <#
    .SYNOPSIS
    Merges two hash tables with the option to remove all null key/value pairs.
     
    .DESCRIPTION
    This function will take two hash tables and merge the second hash table
    to the first. Any keys in the second hash table that exist in the 
     
    .EXAMPLE

    Merge-Hashtables $HashOne $HashTwo
    
    The basic example will merge the two hashtables not removing nulls
    and skipping existing keys from the second hashtable.
    
    Deeper Example:
    ===========================================================================
    PS C:\> $HashOne = @{One='1';Two='2';Three=$null}
    PS C:\> $HashTwo = @{Two='Two';Three='3';Four='4';Five='5'}
    PS C:\> Merge-Hashtables $HashOne $HashTwo

    Name                           Value
    ----                           -----
    Five                           5
    Two                            2
    Three
    One                            1
    Four                           4
    
    .EXAMPLE
    
    Merge-Hashtables $HashOne $HashTwo -RemoveNulValues
    
    This example removes key value pairs that have a value of NULL.
    Also it skips merging existing keys from the second hashtable.
    
    Deeper Example:
    ===========================================================================
    C:\PS> $HashOne = @{One='1';Two='2';Three=$null}
    C:\PS> $HashTwo = @{Two='Two';Three='3';Four='4';Five='5'}
    C:\PS> Merge-Hashtables $HashOne $HashTwo -RemoveNulValues

    Name                           Value
    ----                           -----
    Five                           5
    Two                            2
    One                            1
    Four                           4

    .EXAMPLE
    
    Merge-Hashtables $HashOne $HashTwo -RemoveNulValues -ForceValue
    
    This example removes key value pairs that have a value of NULL.
    Also on existing keys it updates the value with the value from
    the second hashtable.
    
    This example 
    
    Deeper Example:
    ===========================================================================
    PS C:\> $HashOne = @{One='1';Two='2';Three=$null}
    PS C:\> $HashTwo = @{Two='Two';Three='3';Four='4';Five='5'}
    PS C:\> Merge-Hashtables $HashOne $HashTwo -RemoveNulValues -ForceValue

    Name                           Value
    ----                           -----
    Five                           5
    Two                            Two
    Three                          3
    One                            1
    Four                           4

    .NOTES
    Original Author: Norman Skinner (Edgile Inc.) (v-nskin)
    Original Created on: 11/30/2012
    Version: 1.0.0.0
     
    HISTORY:
    ===========#==============#======================================
    Date       | User         | Description
    -----------+--------------+--------------------------------------
    11/30/2012 | v-nskin      | Created script
    -----------+--------------+--------------------------------------
               |              | 
    -----------+--------------+--------------------------------------
               |              | 
    -----------+--------------+--------------------------------------
               |              | 
    -----------+--------------+--------------------------------------
    #>
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true,position=0,HelpMessage= 'Enter the first hashtable to be merged into.')]
        [hashtable]
        # The hashtable to be merged into.
        $HashTable,
        [parameter(Mandatory=$true,position=1,HelpMessage= 'Enter the second hashtable to be merged into the first hashtable.')]
        [hashtable]
        # The second hash table to be merged into the first hash table.
        $HashTableToMerger,
        [switch]
        <#
            If this switch is used, any keys that exist in the first hash table will have their values updated
            with matching keys value in the second hash table.
        #>
        $ForceValue = $false,
        [switch]
        # If this switch is used, all key/value pairs with NULL values will be removed.
        $RemoveNulValues = $false
        
    )

    Set-StrictMode -Version 'Latest'
    $VerbosePreference     = 'Continue'
    $ProgressPreference    = 'SilentlyContinue'
    $ErrorActionPreference = 'Stop'

    foreach($Key in [array]$HashTableToMerger.Keys)
    {
        if ($HashTable.ContainsKey($Key))
        {
            if ($ForceValue)
            {
                # Force the value update for this key
                $HashTable[$Key] = $HashTableToMerger[$Key]
            }
        }
        else
        {
            # Add the new key value pair
            $HashTable.Add($Key, $HashTableToMerger[$Key])
        }
    }
    
    if ($RemoveNulValues)
    {
        foreach($Key in [array]$HashTable.Keys)
        {
            if ($HashTable[$Key] -eq $null)
            {
                $HashTable.Remove($Key)
            }
        }
    }

    Write-Output $HashTable
}

Remove item from a hashtable.

I had an issue removing nulls values from hashtables Key/Value pair. So I wrote a function to make quick work of it.

By converting the hasktables key collection to an array, I do not get an error removing key/value pairs while iterating over the hash.

function Remove-HashtableNulls
{
    <#
    .SYNOPSIS
    Removes any Key pairs that have a NULL value.
     
    .DESCRIPTION
    This function will take a hashtable and iterate over all the
    Key pairs and remove any that have a NULL for the value. It 
    will then return the edited hashtable.
     
    .EXAMPLE
    PS C:\> $TestHash = Remove-HashtableNulls $TestHash
 
    .EXAMPLE
    PS C:\> $TestHash = Remove-HashtableNulls -HashTable $TestHash
 
    .NOTES
    Original Author: Norman Skinner (Edgile Inc.) (Norman.Skinner@Edgile.com)
    Original Created on: 11/30/2012
    Version: 1.0.0.0
     
    HISTORY:
    ===========#================#======================================
    Date       | User           | Description
    -----------+----------------+--------------------------------------
    11/30/2012 | Norman Skinner | Created script
    -----------+----------------+--------------------------------------
               |                | 
    -----------+----------------+--------------------------------------
    #>
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true, HelpMessage= 'Enter a hashtable for null removals.')]
        [hashtable]
        # The hashtable that will have any null valuses removed.
        $HashTable
    )
 
    Set-StrictMode -Version 'Latest'
    $VerbosePreference     = 'Continue'
    $ProgressPreference    = 'SilentlyContinue'
    $ErrorActionPreference = 'Stop'
 
    foreach($Key in [array]$HashTable.Keys)
    {
        if ($HashTable[$Key] -eq $null)
        {
            $HashTable.Remove($Key)
        }
    }
    
    Write-Output $HashTable
}

Wednesday, May 23, 2012

I have too much, Temporal Time on my hands...

Recently I had to write some FIM test automation against some temporal sets. So I needed to be able to run the 'FIM_TemporalEventsJob' in SQL from PowerShell. This would cache my new test users "Date/Time" stamp for the expiration of their group membership. Then when I changed their time stamp the temporal set would fire off the correct MPR's and FIMagic would take place. So to save code repeating I cobbled together information and wrote the following function.
Here is hoping you find it as handy as I did to get work done.

function Invoke-FimTemporal
{
<# 
.SYNOPSIS 
This function will start the 'FIM_TemporalEventsJob' SQL Agent Job. 
  
.DESCRIPTION 
This function will start the 'FIM_TemporalEventsJob' SQL Agent Job
and then wait for the job to finish and then return status.
#>
    param
    (
        [string]
        $server = "MYFIMSERVER"
    )

    ###--------------------------------------------------------------
    ### Verify that SQL agent is running or exit.
    ###--------------------------------------------------------------
    $CheckSqlAgent = Get-Service "SQLSERVERAGENT"
    if ($CheckSqlAgent.Status -ne "Running")
    {
        throw "SQL Server Agent is not running. This script can not continue."
    }
    
    ###--------------------------------------------------------------
    ### Start the FIM_TemporalEventsJob SQL Agent Job.
    ###--------------------------------------------------------------
    [void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
    [void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
    $SqlServer = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
    $jobsrv = $SqlServer.JobServer
    $FimTemporalJob = $jobsrv.Jobs | where {$_.name -like "FIM_TemporalEventsJob"}
    $LastRun = $FimTemporalJob.LastRunDate
    Write-Verbose ("Last run was [{0}]." -f $LastRun)
    Write-Verbose "Starting the FIM_TemporalEventsJob."
    $FimTemporalJob.Start()

    ###--------------------------------------------------------------
    ### Wait for the FIM_TemporalEventsJob SQL Agent Job to complete.
    ###--------------------------------------------------------------
    Write-Verbose ("Waiting for the FIM_TemporalEventsJob to complete. Started [{0}]." -f (get-date))
    do {
        Start-Sleep -Seconds 10
        $FimTemporalJob.Refresh()
    }
    while ($LastRun -eq $FimTemporalJob.LastRunDate)
    Write-Verbose ("FIM_TemporalEventsJob completed at [{0}]." -f (get-date))
    Write-Verbose ("FIM_TemporalEventsJob completed with a status of [{0}]." -f $FimTemporalJob.LastRunOutcome)
    Write-Output $FimTemporalJob.LastRunOutcome
}

Thursday, February 23, 2012

PowerShell IsEmptyOrNull?

The current version of PowerShell allows for a quick and easy way to check if a variable is NULL or EMPTY. Just place the variable as the condition of an "IF" statment. Here is an example with an array:

# Set $a as an EMPTY array
$a = @()

# Now test it
if ($a) { Write-Host "has value" }
else { Write-Host "NULL or EMPTY"}

# Set $a as a NULL
$a = $null

# Now test it
if ($a) { Write-Host "has value" }
else { Write-Host "NULL or EMPTY"}

The output is:

NULL or EMPTY
NULL or EMPTY

There you have it. I tend to use beacuse it looks clean, but as I like to say, "Programming is an Art, and there are a lot of crappy painters out there".