Custom Actions

Custom Actions are a feature enabling users to execute a script when an item from the shop is ordered, approved and declined. This could for instance be used to add the order details to your own database / management system.

Custom Actions are found under “Software Administration” for packages, applications and software groups and under Custom Shop Items.

Click Edit on a package or item and go to the “Custom Action” / “Action” tab:

Software Administration:

Custom Shop Items:

You can select 2 scripts for each item. A script that will be executed when the item is ordered from the shop and a script that will be executed when the item is approved or declined.

Only PowerShell and VB Scripts are supported.

You can upload a new script by clicking on the “Select” button or you can choose an existing from the drop-down box:

Scripts will be uploaded to “<SoftwareCentral install dir>\Uploads\CustomScripts\”. Existing scripts are located at this folder.

If you have multiple installations of SoftwareCentral using the same database, you will need to manually copy the scripts to each installation.

For each script you can add arguments and parameters:

The parameters are variables that can be passed to the script from SoftwareCentral. See the next pages for examples.

 

The command line will be generated in the following format:

[arguments] [“filepath\scribtname.vbs”] [parameters]

 

VBScript example:

“Cscript.exe //b “C:\inetpub\SoftwareCentral\Uploads\CustomScripts\YourScript.vbs” /ResourceID:123456 /Username:domain\username”

 

PowerShell Script example:

“PowerShell.exe -file “C:\inetpub\SoftwareCentral\Uploads\CustomScripts\YourScript.ps1” -ResourceID 123456 -Username domain\username”

 

The filepath is added automatically, so do not add it manually.

Parameters

The available parameters varies for the different items.

Available to all:

-          ResourceID : Integer - The resource id of the computer that made the order.

-          Username : String - The “domain\username” of the user who made the order.

-          OrderID : Integer - The ID of the order itself.

Available to some:

-          RequiresApproval : String - “true” if the order needs approval, else “false”.

-          Action : String - For new orders, it will return the action, “install”, “rerun” or “uninstall”. For orders that are approved or declined, it will return “approved” or “declined”.

-          PackageID : String - The ID of the ordered package, application or software group

-          ShopItemID : Integer - The ID of the ordered Custom Shop Item.

-          SoftwareOrderItemID: Integer - The ID of the item. This ID can be used to approve / decline orders.

 

For security reasons Software Variables are not passed as parameters. Instead they can be found using the web service WS_SoftwareVariables (See the Web Service section on page 53for more details.)

 

Security

Scripts does not automatically run in the context of the application pool user. For each script, you will have to define the windows account that will execute the script.

Make sure that the account has the proper permissions to execute the script. If the script interacts with databases or other resources, the account will also need the proper permissions to access those resources.

Note that when debugging scripts or if you require that the script can write to the SoftwareCentral log, it must run as the application pool user.

Accounts other than the application pool user requires the "Log on as a batch job" permission, either from the Local Security Policy on the IIS server or via a group policy.

The application pool user must be granted the "Replace a process level token", "Adjust memory quotas for a process" and "Act as part of the operating system" permissions.

 

An account must be selected for each script:

Use the "+" button to add a new user. Users can be managed from the Password Manager interface.

 

VBScript Example Code

The following script will get the ResourceID, Username, OrderId, RequiresApproval, Action and PackageID or ShopItemID and write them all to a text file.

In SoftwareCentral, the configuration looks like this:

The actual script, “VBScriptExampleOrdered.vbs”, is included in the installation and can be selected from the “Existing” drop-down box.

VBScriptExampleOrdered.vbs
Copy Code
' SoftwareCentral VBScript Example
'
' This script reads the parameters from SoftwareCentral and writes them to a text file.
'
' Get current username (RunAs in SoftwareCentral)
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )
' Load parameters into the output string
output = "RunAs: " & strUserName &_
        " ResourceID: " & WScript.Arguments.Named("ResourceID") &_
        " Username: " & WScript.Arguments.Named("Username") &_
        " OrderID: " & WScript.Arguments.Named("OrderID") &_
        " RequiresApproval: " & WScript.Arguments.Named("RequiresApproval") &_
        " Action: " & WScript.Arguments.Named("Action") &_
        " PackageID: " & WScript.Arguments.Named("PackageID") &_
        " ShopItemID: " & WScript.Arguments.Named("ShopItemID")
' Write values to a text file
WriteFileText "c:\temp\SoftwareCentralVBScriptExampleOutput.txt", output
Function WriteFileText(sFilePath, sText)
    Dim objFSO
    Dim objTextFile
   
    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8
   
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(sFilePath) Then
        Set objTextFile = objFSO.OpenTextFile(sFilePath, ForAppending, True)
    Else
        Set objTextFile = objFSO.CreateTextFile(sFilePath, True)
    End If
   
    objTextFile.WriteLine (sText)
    objTextFile.Close
End Function


Below is a snapshot of the script:

At line 10 and below, we read the parameters we selected in SoftwareCentral.

At line 20 the parameters are written to a text file.

PowerShell Example Code

The following script will get the ResourceID, Username, OrderId, Action and PackageID or ShopItemID and write them all to a text file.

In SoftwareCentral, the configuration looks like this:

The actual script, “PowerShellExampleReviewed”, is included in the installation and can be selected from the “Existing” drop-down box.

PowerShellExampleReviewed.ps1
Copy Code
# SoftwareCentral PowerShell Example
#
# This script reads the parameters from SoftwareCentral and writes them to a text file.
#
# Load parameters:
Param
(
[Int32]$ResourceID,
[string]$Username,
[Int32]$OrderID,
[string]$Action,
[string]$PackageID,
[Int32]$ShopItemID
)
# Get current username (RunAs in SoftwareCentral)
$runas = [Environment]::UserName
$output =
(
"RunAs: "+$runas+
" ResourceID: "+$ResourceID+
" Username: "+$Username+
" OrderID: "+$OrderID+
" Action: "+$Action+
" PackageID: "+$PackageID+
" ShopItemID: "+$ShopItemID
)
# Write values to a text file
Add-Content -Value $output -Path C:\Temp\SoftwareCentralPowerShellExampleOutput.txt

 

Web Service for Software Variables

When configuring a package or custom shop item for the shop, you can add some software variables that the user must fill in before an item is ordered. To retrieve this data in your script you can call the web service “WS_SoftwareVariables”.

The web service has two functions:

GetSoftwareVariablesForPackage, which requires 3 paramters, the SoftwareVariableName, the OrderID and the PackageID.

GetSoftwareVariablesForCustomShopItem, which requires 3 parameters, the SoftwareVariableName, the OrderID and the ShopItemID.

They will both return a string with the software variable value. If no value are found, the string will be empty.

 

A VBScript that demonstrates how to call this web service can be found at “<SoftwareCentral install dir>\Tools\CustomShopItemScriptExamples\GetSoftwareVariable.vbs”.

GetSoftwareVariable.vbs
Copy Code
'================================Version 1.0===============================
' NAME: Get Software Variable
'
' AUTHOR: SoftwareCentral
' DATE  : 15-07-2014
'
' COMMENT:
' This script returns a Software Variable Value for a given Software Variable, Order and Package
'
' ** SET THE swcAddress VARIABLE **
' ** SET THE softwareVariableName VARIABLE **
'==========================================================================
'======================Variables that can be modified======================
' ** The SoftwareCentral address. E.g.: http://swc or http://localhost:8080
swcAddress = "http://localhost:8080"
' ** The Software Variable Name. E.g.: "SupportReason"
softwareVariableName = "SupportReason"
'==========================================================================
'Load properties from SoftwareCentral
orderId = WScript.Arguments.Named("OrderID")
packageId = WScript.Arguments.Named("PackageID")
'shopItemId = WScript.Arguments.Named("ShopItemID")
'The object that will make the call to the WS
Set oXMLHTTP = CreateObject("Microsoft.XMLHTTP")
'The object that will receive the answer from the WS
Set oXMLDoc = CreateObject("Microsoft.XMLDOM")
GetVariableValue()
Function GetVariableValue()
    'Set the name of the subroutine that will handle the response
    oXMLHTTP.onreadystatechange = getRef("HandleStateChange")
    'Initialize the request
    oXMLHTTP.open "POST", swcAddress & "/WebServices/WS_SoftwareVariables.asmx/GetSoftwareVariablesForPackage", False
    'oXMLHTTP.open "POST", swcAddress & "/WebServices/WS_SoftwareVariables.asmx/GetSoftwareVariablesForCustomShopItem", False
    'Content type
    oXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    
    'Send the request to the Web Service
    oXMLHTTP.send "softwareVariableName=" & softwareVariableName &_
                  "&orderId=" & orderId &_
                  "&packageId=" & packageId
                  '"&shopItemId=" & shopItemId
End Function
Sub HandleStateChange()
    Dim szResponse
    'When the call has been completed (ready state 4)
    If oXMLHTTP.readyState = 4 Then
        szResponse = oXMLHTTP.responseText
        oXMLDoc.loadXML szResponse
        'If the WS response is not in XML format, there is a problem
        If oXMLDoc.parseError.errorCode <> 0 Then
            WScript.Echo "ERROR:"
            WScript.Echo oXMLHTTP.responseText
            WScript.Echo oXMLDoc.parseError.reason
        Else
            WScript.Echo "Software Variable Value: " & oXMLDoc.getElementsByTagName("string")(0).childNodes(0).Text   
        End If
    End If
End Sub

 

It calls the function “GetSoftwareVariablesForPackage” and adds the 3 parameters, SoftwareVariableName, OrderID and PackageID.

Line 61 below, reads out the variable value, as the user entered:


 

Debugging Scripts

Your scripts outputs and error messages are sent to SoftwareCentral and saved in the log.


VBScripts

You can use WScript.Echo to send an output to SoftwareCentral. 
You can also use the standard streams:

Streams
Copy Code
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."  


Powershell Scripts

You can use Write-Host to write to the standard output.

You can use $host.ui.WriteErrorLine to write to the error output.

 

You may also use the following function to write to the error output:

Powershell Write-StdErr
Copy Code
function Write-StdErr 
{
     param ([PSObject] $InputObject)
     $outFunc =
     if ($Host.Name -eq 'ConsoleHost')
     {
          [Console]::Error.WriteLine
     }
     else
     {
         $host.ui.WriteErrorLine
     }
     if ($InputObject)
     {
         [void] $outFunc.Invoke($InputObject.ToString())
     }
     else
     {
         [string[]] $lines = @()
         $Input | % { $lines += $_.ToString() }
         [void] $outFunc.Invoke($lines -join "`r`n")
     }
}

E.g.:

Example
Copy Code
Write-Host “This will go to standard output."
Write-StdErr “This will go to error output."

 

 


© Copyright - SoftwareCentral

https://softwarecentral.cloud/help