├── .gitignore
├── DocumentPowerShell.ps1
├── Get-HelpByMarkdown.ps1
├── LICENSE
├── README.md
├── St2.Client.PowerShell
├── BaseClientCmdlet.cs
├── GetActionsCmdlet.cs
├── GetExecutionsCmdlet.cs
├── GetPacksCmdlet.cs
├── GetRulesCmdlet.cs
├── InstallPackCmdlet.cs
├── InvokeActionCmdlet.cs
├── NewActionCmdlet.cs
├── NewActionParameterCmdlet.cs
├── NewSt2ClientConnection.cs
├── Properties
│ └── AssemblyInfo.cs
├── RemoveActionCmdlet.cs
├── RemoveRuleCmdlet.cs
├── SessionStateExtensions.cs
├── St2.Client.Help.pshproj
├── St2.Client.PowerShell.csproj
├── St2.Client.PowerShell.csproj.user
├── St2.Client.PowerShell.dll-Help.xml
├── St2.Client.PowerShell.nuspec
├── St2.Client.psd1
└── St2ClientConnection.cs
├── St2.Client.sln
├── St2.Client
├── Apis
│ ├── ActionsApi.cs
│ ├── ExecutionsApi.cs
│ ├── IActionsApi.cs
│ ├── IExecutionsApi.cs
│ ├── IPacksApi.cs
│ ├── IRulesApi.cs
│ ├── PacksApi.cs
│ └── RulesApi.cs
├── AuthExtensions.cs
├── Exceptions
│ ├── ExceptionFactory.cs
│ ├── FailedRequestException.cs
│ └── InvalidTokenException.cs
├── ISt2Client.cs
├── Models
│ ├── Action.cs
│ ├── ActionParameter.cs
│ ├── CreateAction.cs
│ ├── ExecuteActionRequest.cs
│ ├── Execution.cs
│ ├── ExecutionContext.cs
│ ├── NamedActionParameter.cs
│ ├── Pack.cs
│ ├── ParameterType.cs
│ ├── PayloadSchema.cs
│ ├── Rule.cs
│ ├── RuleAction.cs
│ ├── RuleType.cs
│ ├── Runner.cs
│ ├── RunnerEnvironment.cs
│ ├── RunnerParameter.cs
│ ├── RunnerType.cs
│ ├── TokenResponse.cs
│ ├── Trigger.cs
│ ├── TriggerInstance.cs
│ └── TriggerType.cs
├── Properties
│ └── AssemblyInfo.cs
├── St2.Client.csproj
├── St2.Client.nuspec
├── St2Client.cs
└── packages.config
├── appveyor.yml
├── docs
├── St2.Client.md
├── index.md
└── powershell
│ ├── Get-St2Actions.md
│ ├── Get-St2Executions.md
│ ├── Get-St2Packs.md
│ ├── Get-St2Rules.md
│ ├── Install-St2Pack.md
│ ├── Invoke-St2Action.md
│ ├── New-St2Action.md
│ ├── New-St2ActionParameter.md
│ ├── New-St2ClientConnection.md
│ ├── Remove-St2Action.md
│ ├── Remove-St2Rule.md
│ └── index.md
├── nuget
├── NuGet.exe
├── nuget-anycpu.exe
└── pack.ps1
└── xmldoc2md
├── App.config
├── LICENSE
├── Program.cs
├── Properties
└── AssemblyInfo.cs
├── README.md
├── XmlDoc2MD.csproj
├── XmlDoc2MD.sln
├── xmldoc2md.md
├── xmldoc2md.ps1
└── xmldoc2md.xsl
/.gitignore:
--------------------------------------------------------------------------------
1 | packages/
2 | St2.Client/obj/
3 | St2.Client.PowerShell/bin/
4 | St2.Client.PowerShell/obj/
5 | St2.Client/bin/
6 | *.suo
7 | *.Cache
8 |
--------------------------------------------------------------------------------
/DocumentPowerShell.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [string] $apiKey
3 | )
4 |
5 | Import-Module .\St2.Client.PowerShell\bin\Release\St2.Client.psd1
6 | $commands = Get-Command -Module St2.Client
7 |
8 | if((Test-Path ".\docs\powershell\") -eq 0){
9 | mkdir ".\docs\powershell\"}
10 | foreach ($command in $commands){
11 | .\Get-HelpByMarkdown.ps1 $command.name | Set-Content -Encoding utf8 .\docs\powershell\$command.md
12 | }
13 | $modPath = $Env:PSModulePath.split(';')[1]
14 | mkdir "$($modPath)\St2.Client"
15 | # Install the module
16 | Copy-Item .\St2.Client.PowerShell\bin\Release\*.* "$($modPath)\St2.Client" -Verbose
17 |
18 | # publish the module
19 | Publish-Module -NuGetApiKey $apiKey -Path "$($modPath)\St2.Client"
--------------------------------------------------------------------------------
/Get-HelpByMarkdown.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # File: Get-HelpByMarkdown.ps1
3 | #
4 | # Author: Akira Sugiura (urasandesu@gmail.com)
5 | #
6 | #
7 | # Copyright (c) 2014 Akira Sugiura
8 | #
9 | # This software is MIT License.
10 | #
11 | # Permission is hereby granted, free of charge, to any person obtaining a copy
12 | # of this software and associated documentation files (the "Software"), to deal
13 | # in the Software without restriction, including without limitation the rights
14 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 | # copies of the Software, and to permit persons to whom the Software is
16 | # furnished to do so, subject to the following conditions:
17 | #
18 | # The above copyright notice and this permission notice shall be included in
19 | # all copies or substantial portions of the Software.
20 | #
21 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 | # THE SOFTWARE.
28 | #
29 |
30 | <#
31 | .SYNOPSIS
32 | Gets the comment-based help and converts to GitHub Flavored Markdown.
33 |
34 | .PARAMETER Name
35 | A command name to get comment-based help.
36 |
37 | .EXAMPLE
38 | & .\Get-HelpByMarkdown.ps1 Select-Object > .\Select-Object.md
39 |
40 | DESCRIPTION
41 | -----------
42 | This example gets comment-based help of `Select-Object` command, and converts GitHub Flavored Markdown format, then saves it to `Select-Object.md` in current directory.
43 |
44 | .INPUTS
45 | System.String
46 |
47 | .OUTPUTS
48 | System.String
49 |
50 | #>
51 |
52 | [CmdletBinding()]
53 | param (
54 | [Parameter(Mandatory = $True)]
55 | $Name
56 | )
57 |
58 | function EncodePartOfHtml {
59 | param (
60 | [string]
61 | $Value
62 | )
63 |
64 | ($Value -replace '<', '<') -replace '>', '>'
65 | }
66 |
67 | function GetCode {
68 | param (
69 | $Example
70 | )
71 | $codeAndRemarks = (($Example | Out-String) -replace ($Example.title), '').Trim() -split "`r`n"
72 |
73 | $code = New-Object "System.Collections.Generic.List[string]"
74 | for ($i = 0; $i -lt $codeAndRemarks.Length; $i++) {
75 | if ($codeAndRemarks[$i] -eq 'DESCRIPTION' -and $codeAndRemarks[$i + 1] -eq '-----------') {
76 | break
77 | }
78 | if (1 -le $i -and $i -le 2) {
79 | continue
80 | }
81 | $code.Add($codeAndRemarks[$i])
82 | }
83 |
84 | $code -join "`r`n"
85 | }
86 |
87 | function GetRemark {
88 | param (
89 | $Example
90 | )
91 | $codeAndRemarks = (($Example | Out-String) -replace ($Example.title), '').Trim() -split "`r`n"
92 |
93 | $isSkipped = $false
94 | $remark = New-Object "System.Collections.Generic.List[string]"
95 | for ($i = 0; $i -lt $codeAndRemarks.Length; $i++) {
96 | if (!$isSkipped -and $codeAndRemarks[$i - 2] -ne 'DESCRIPTION' -and $codeAndRemarks[$i - 1] -ne '-----------') {
97 | continue
98 | }
99 | $isSkipped = $true
100 | $remark.Add($codeAndRemarks[$i])
101 | }
102 |
103 | $remark -join "`r`n"
104 | }
105 |
106 | try {
107 | if ($Host.UI.RawUI) {
108 | $rawUI = $Host.UI.RawUI
109 | $oldSize = $rawUI.BufferSize
110 | $typeName = $oldSize.GetType().FullName
111 | $newSize = New-Object $typeName (500, $oldSize.Height)
112 | $rawUI.BufferSize = $newSize
113 | }
114 |
115 | $full = Get-Help $Name -Full
116 |
117 | @"
118 | $($full.Name)
119 | ===================
120 |
121 | ## SYNOPSIS
122 | $($full.Synopsis)
123 |
124 | ## SYNTAX
125 | ``````powershell
126 | $((($full.syntax | Out-String) -replace "`r`n", "`r`n`r`n").Trim())
127 | ``````
128 |
129 | ## DESCRIPTION
130 | $(($full.description | Out-String).Trim())
131 |
132 | ## PARAMETERS
133 | "@ + $(foreach ($parameter in $full.parameters.parameter) {
134 | @"
135 |
136 | ### -$($parameter.name) <$($parameter.type.name)>
137 | $(($parameter.description | Out-String).Trim())
138 | ``````
139 | $(((($parameter | Out-String).Trim() -split "`r`n")[-5..-1] | % { $_.Trim() }) -join "`r`n")
140 | ``````
141 |
142 | "@
143 | }) + @"
144 |
145 | ## INPUTS
146 | $($full.inputTypes.inputType.type.name)
147 |
148 | ## OUTPUTS
149 | $($full.returnValues.returnValue[0].type.name)
150 |
151 | ## NOTES
152 | $(($full.alertSet.alert | Out-String).Trim())
153 |
154 | ## EXAMPLES
155 | "@ + $(foreach ($example in $full.examples.example) {
156 | @"
157 |
158 | ### $(($example.title -replace '-*', '').Trim())
159 | ``````powershell
160 | $(GetCode $example)
161 | ``````
162 | $(GetRemark $example)
163 |
164 | "@
165 | }) + @"
166 |
167 | "@
168 |
169 | } finally {
170 | if ($Host.UI.RawUI) {
171 | $rawUI = $Host.UI.RawUI
172 | $rawUI.BufferSize = $oldSize
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # St2Client
2 |
3 | [](https://ci.appveyor.com/project/tonybaloney/st2client)
4 | [](https://www.nuget.org/packages/St2.Client/)
5 |
6 | A StackStorm API client for C#.NET including a PowerShell module
7 |
8 | ## Using the C#.NET client
9 |
10 | ### Documentation
11 |
12 | The docs are available on readthedocs.org
13 | [](http://st2client.readthedocs.org/en/latest/)
14 |
15 | ### Download packages
16 | The .NET client is available on nuget.org
17 | * Release - [](https://www.nuget.org/packages/St2.Client/)
18 | The PowerShell module is available on nuget.org
19 | * Release - [](https://www.nuget.org/packages/St2.Client.PowerShell/)
20 |
21 | ### Example
22 |
23 | ```csharp
24 | St2Client apiClient = new St2Client("http://12.3.2.3:9100", "http://12.3.2.3:9101", "testu", "testp");
25 | // login and get a token
26 | await apiClient.RefreshTokenAsync();
27 |
28 | var actions = await apiClient.Actions.GetActionsAsync();
29 | ```
30 |
31 | ## Using the PowerShell module
32 |
33 | The PowerShell Module includes the following commands:
34 |
35 | * New-St2ClientConnection - Creates a new connection object
36 | * Get-St2Actions - Get the actions (can filter by pack name)
37 | * Get-St2Packs - Get the packs available
38 | * Get-St2Executions - Get the executions
39 | * Remove-St2Action - Delete an Action
40 | * Invoke-St2Action - Invoke an Action
41 |
42 | ```powershell
43 | Import-Module .\St2.Client.Powershell.dll
44 | $conn = New-St2ClientConnection -Username testu -Password testp -ApiUrl "http://12.3.2.3:9101" -AuthApiUrl "http://12.3.2.3:9100"
45 |
46 | $MyPack = Get-St2Packs -Name "example"
47 |
48 | $actions = Get-St2Actions -Pack $MyPack
49 |
50 | foreach($action in $actions){
51 | Write-Output "Getting executions for action $action.name"
52 | Get-St2Executions -Action $action -Connection $conn
53 | }
54 |
55 | $action = Get-St2Actions -PackName "st2_dimensiondata" -Name "list_locations"
56 | Invoke-St2Action -Action $action -Parameters @{"region"="dd-au"}
57 |
58 | ```
59 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/BaseClientCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System.Management.Automation;
2 | using System.Security.Authentication;
3 |
4 | namespace TonyBaloney.St2.Client.PowerShell
5 | {
6 | public abstract class BaseClientCmdlet
7 | : PSCmdlet
8 | {
9 | [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true,
10 | HelpMessage = "The StackStorm Connection created by New-St2ClientConnection")]
11 | public St2ClientConnection Connection { get; set; }
12 |
13 | ///
14 | /// The begin processing.
15 | ///
16 | protected override void BeginProcessing()
17 | {
18 | base.BeginProcessing();
19 |
20 | // If CaaS connection is NOT set via parameter, get it from the PS session
21 | if (Connection == null)
22 | {
23 | Connection = SessionState.GetDefaultServiceConnection();
24 | if (Connection == null)
25 | ThrowTerminatingError(
26 | new ErrorRecord(
27 | new AuthenticationException(
28 | "Cannot find a valid connection. Use New-St2ClientConnection to create or Set-St2ActiveConnection to set a valid connection"),
29 | "-1",
30 | ErrorCategory.AuthenticationError,
31 | this));
32 | }
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/GetActionsCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Management.Automation;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.PowerShell
7 | {
8 | using Action = Models.Action;
9 |
10 | [Cmdlet(VerbsCommon.Get, "St2Actions")]
11 | public class GetActionsCmdlet
12 | : BaseClientCmdlet
13 | {
14 | [Parameter(Mandatory = false, HelpMessage = "Actions for a particular pack")] public Pack Pack;
15 |
16 | [Parameter(Mandatory = false, HelpMessage = "Actions for a particular pack")] public string PackName;
17 |
18 | [Parameter(Mandatory = false, HelpMessage = "Actions with name")] public string Name;
19 |
20 | protected override void ProcessRecord()
21 | {
22 | base.ProcessRecord();
23 |
24 | try
25 | {
26 | IList actions;
27 | if (Pack != null)
28 | PackName = Pack.name;
29 |
30 | if (!String.IsNullOrWhiteSpace(PackName))
31 | {
32 | if (!String.IsNullOrWhiteSpace(Name))
33 | actions = Connection.ApiClient.Actions.GetActionsForPackByNameAsync(PackName, Name).Result;
34 | else
35 | {
36 | actions = Connection.ApiClient.Actions.GetActionsForPackByNameAsync(PackName, Name).Result;
37 | }
38 | }
39 | else if (!String.IsNullOrWhiteSpace(Name))
40 | actions = Connection.ApiClient.Actions.GetActionsByNameAsync(Name).Result;
41 | else
42 | {
43 | actions = Connection.ApiClient.Actions.GetActionsAsync().Result;
44 | }
45 |
46 | foreach (var action in actions)
47 | {
48 | WriteObject(action);
49 | }
50 | }
51 | catch (AggregateException ae)
52 | {
53 | ae.Handle(
54 | e =>
55 | {
56 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
57 |
58 | return true;
59 | });
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/GetExecutionsCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Management.Automation;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.PowerShell
7 | {
8 | using Action = Models.Action;
9 |
10 | [Cmdlet(VerbsCommon.Get, "St2Executions")]
11 | public class GetExecutionsCmdlet
12 | : BaseClientCmdlet
13 | {
14 | [Parameter(Mandatory = false, HelpMessage = "Limit the number of results")] public int Limit=5;
15 |
16 | [Parameter(Mandatory = false, HelpMessage = "Show executions for a particular action")] public string ActionName;
17 |
18 | [Parameter(Mandatory = false, HelpMessage = "Show executions for a particular action")] public Action Action;
19 |
20 | protected override void ProcessRecord()
21 | {
22 | base.ProcessRecord();
23 |
24 | try
25 | {
26 | IList executions;
27 |
28 | if (Action != null)
29 | {
30 | executions = Connection.ApiClient.Executions.GetExecutionsForActionAsync(Action.name, Limit).Result;
31 | }
32 | else if (!string.IsNullOrWhiteSpace(ActionName))
33 | executions = Connection.ApiClient.Executions.GetExecutionsForActionAsync(ActionName).Result;
34 | else
35 | {
36 | executions = Connection.ApiClient.Executions.GetExecutionsAsync(Limit).Result;
37 | }
38 |
39 |
40 | foreach (var exec in executions)
41 | {
42 | WriteObject(exec);
43 | }
44 | }
45 | catch (AggregateException ae)
46 | {
47 | ae.Handle(
48 | e =>
49 | {
50 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
51 |
52 | return true;
53 | });
54 | }
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/GetPacksCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Management.Automation;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.PowerShell
7 | {
8 | [Cmdlet(VerbsCommon.Get, "St2Packs")]
9 | public class GetPacksCmdlet
10 | : BaseClientCmdlet
11 | {
12 | [Parameter(Mandatory = false, HelpMessage = "Packs with ID")]
13 | public string Id;
14 |
15 | [Parameter(Mandatory = false, HelpMessage = "Packs with name")]
16 | public string Name;
17 |
18 | protected override void ProcessRecord()
19 | {
20 | base.ProcessRecord();
21 | try
22 | {
23 | IList packs;
24 |
25 | if (!string.IsNullOrWhiteSpace(Name))
26 | packs = Connection.ApiClient.Packs.GetPacksByNameAsync(Name).Result;
27 | else if (!string.IsNullOrWhiteSpace(Id))
28 | packs = Connection.ApiClient.Packs.GetPacksByIdAsync(Id).Result;
29 | else
30 | packs = Connection.ApiClient.Packs.GetPacksAsync().Result;
31 |
32 | foreach (var pack in packs)
33 | {
34 | WriteObject(pack);
35 | }
36 | }
37 | catch (AggregateException ae)
38 | {
39 | ae.Handle(
40 | e =>
41 | {
42 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
43 |
44 | return true;
45 | });
46 | }
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/GetRulesCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Management.Automation;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.PowerShell
7 | {
8 | [Cmdlet(VerbsCommon.Get, "St2Rules")]
9 | public class GetRulesCmdlet
10 | : BaseClientCmdlet
11 | {
12 | [Parameter(Mandatory = false, HelpMessage = "Show rules for a particular pack")] public string PackName;
13 |
14 | [Parameter(Mandatory = false, HelpMessage = "Show rules for a particular pack")] public Pack Pack;
15 |
16 | protected override void ProcessRecord()
17 | {
18 | base.ProcessRecord();
19 |
20 | try
21 | {
22 | IList rules;
23 |
24 | if (Pack != null)
25 | {
26 | rules = Connection.ApiClient.Rules.GetRulesForPackAsync(Pack.name).Result;
27 | }
28 | else if (!string.IsNullOrWhiteSpace(PackName))
29 | rules = Connection.ApiClient.Rules.GetRulesForPackAsync(PackName).Result;
30 | else
31 | {
32 | rules = Connection.ApiClient.Rules.GetRulesAsync().Result;
33 | }
34 |
35 |
36 | foreach (var exec in rules)
37 | {
38 | WriteObject(exec);
39 | }
40 | }
41 | catch (AggregateException ae)
42 | {
43 | ae.Handle(
44 | e =>
45 | {
46 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
47 |
48 | return true;
49 | });
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/InstallPackCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Management.Automation;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.PowerShell
7 | {
8 | [Cmdlet(VerbsLifecycle.Install, "St2Pack")]
9 | public class InstallPackCmdlet
10 | : BaseClientCmdlet
11 | {
12 | [Parameter(Mandatory = true, HelpMessage = "Name of the pack to install")]
13 | public string Name;
14 |
15 | [Parameter(Mandatory = false, HelpMessage = "URL of the repository")]
16 | public string RepoUrl;
17 |
18 | [Parameter(Mandatory = false, HelpMessage = "Branch of the repository")]
19 | public string Branch;
20 |
21 | protected override void ProcessRecord()
22 | {
23 | base.ProcessRecord();
24 |
25 | try
26 | {
27 | Dictionary parameters = new Dictionary();
28 |
29 | string[] pack_names = {Name};
30 | parameters.Add("packs", pack_names);
31 |
32 | if (!string.IsNullOrWhiteSpace(RepoUrl))
33 | parameters.Add("repo_url", RepoUrl);
34 |
35 | if (!string.IsNullOrWhiteSpace(Branch))
36 | parameters.Add("branch", Branch);
37 |
38 | Execution result = Connection.ApiClient.Executions.ExecuteActionAsync("packs.install", parameters).Result;
39 | WriteObject(result);
40 | }
41 | catch (AggregateException ae)
42 | {
43 | ae.Handle(
44 | e =>
45 | {
46 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
47 |
48 | return true;
49 | });
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/InvokeActionCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Management.Automation;
6 | using TonyBaloney.St2.Client.Models;
7 |
8 | namespace TonyBaloney.St2.Client.PowerShell
9 | {
10 | using Action = Models.Action;
11 |
12 | /// An invoke action cmdlet.
13 | ///
14 | [Cmdlet(VerbsLifecycle.Invoke, "St2Action")]
15 | public class InvokeActionCmdlet
16 | : BaseClientCmdlet
17 | {
18 | [Parameter(Mandatory = true, HelpMessage = "Action execution parameters")]
19 | public Hashtable Parameters;
20 |
21 | [Parameter(Mandatory = true, HelpMessage = "The name of the action to execute", ParameterSetName = "byName")]
22 | public string ActionName;
23 |
24 | [Parameter(Mandatory = true, HelpMessage = "The action to execute", ParameterSetName = "byObj")]
25 | public Action Action;
26 |
27 | protected override void ProcessRecord()
28 | {
29 | base.ProcessRecord();
30 |
31 | try
32 | {
33 | Execution result;
34 |
35 | Dictionary parameters =
36 | Parameters.Keys.Cast().ToDictionary(key => key, key => Parameters[key].ToString());
37 |
38 | if (!string.IsNullOrWhiteSpace(ActionName))
39 | result = Connection.ApiClient.Executions.ExecuteActionAsync(ActionName, parameters).Result;
40 | else
41 | {
42 | result = Connection.ApiClient.Executions.ExecuteActionAsync(Action.@ref, parameters).Result;
43 | }
44 |
45 | WriteObject(result);
46 | }
47 | catch (AggregateException ae)
48 | {
49 | ae.Handle(
50 | e =>
51 | {
52 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
53 |
54 | return true;
55 | });
56 | }
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/NewActionCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Management.Automation;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.PowerShell
7 | {
8 | [Cmdlet(VerbsCommon.New, "St2Action")]
9 | public class NewActionCmdlet
10 | : BaseClientCmdlet
11 | {
12 | [Parameter(Mandatory = true, HelpMessage = "Name of the action")]
13 | public string Name;
14 |
15 | [Parameter(Mandatory = true, HelpMessage = "Description of the action")]
16 | public string Description;
17 |
18 | [Parameter(Mandatory = true, HelpMessage = "Entry point (script to run)")]
19 | public string EntryPoint;
20 |
21 | [Parameter(Mandatory = true, HelpMessage = "Collection of parameters for the action")]
22 | public NamedActionParameter[] Parameters { get; set; }
23 |
24 | [Parameter(Mandatory = true, HelpMessage = "The target pack", ParameterSetName = "ByObj")]
25 | public Pack Pack;
26 |
27 | [Parameter(Mandatory = true, HelpMessage = "Name of the target pack", ParameterSetName = "ByName")]
28 | public string PackName;
29 |
30 | [Parameter(Mandatory = true, HelpMessage = "Type of runner for the action")]
31 | public RunnerType RunnerType { get; set; }
32 |
33 | protected override void ProcessRecord()
34 | {
35 | base.ProcessRecord();
36 |
37 | try
38 | {
39 | if (Pack != null)
40 | PackName = Pack.name;
41 |
42 | var Action = Connection.ApiClient.Actions.CreateActionAsync(new CreateAction
43 | {
44 | description = Description,
45 | enabled = true,
46 | entry_point = EntryPoint,
47 | name = Name,
48 | pack = PackName,
49 | parameters = Parameters.ToDictionary(item => item.name, item => (ActionParameter)item),
50 | runner_type = Enum.GetName(typeof(RunnerType), RunnerType)
51 | }).Result;
52 |
53 | WriteObject(Action);
54 | }
55 | catch (AggregateException ae)
56 | {
57 | ae.Handle(
58 | e =>
59 | {
60 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
61 |
62 | return true;
63 | });
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/NewActionParameterCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System.Management.Automation;
2 | using TonyBaloney.St2.Client.Models;
3 |
4 | namespace TonyBaloney.St2.Client.PowerShell
5 | {
6 | [Cmdlet(VerbsCommon.New, "St2ActionParameter")]
7 | public class NewActionParameterCmdlet
8 | : PSCmdlet
9 | {
10 | [Parameter(Mandatory = true, HelpMessage = "The name of the parameter")]
11 | public string Name { get; set; }
12 |
13 | [Parameter(Mandatory = true, HelpMessage = "The type of the parameter")]
14 | public ParameterType Type { get; set; }
15 |
16 | [Parameter(Mandatory = true, HelpMessage = "Description of the parameter")]
17 | public string Description { get; set; }
18 |
19 | [Parameter(Mandatory = true, HelpMessage = "Is immutable")]
20 | public bool Immutable { get; set; }
21 |
22 | [Parameter(Mandatory = true, HelpMessage = "Is immutable")]
23 | public bool Required { get; set; }
24 |
25 | [Parameter(Mandatory = true, HelpMessage = "The name of the parameter")]
26 | public object DefaultValue { get; set; }
27 |
28 | protected override void ProcessRecord()
29 | {
30 | base.ProcessRecord();
31 |
32 | WriteObject(new NamedActionParameter
33 | {
34 | @default = DefaultValue,
35 | description = Description,
36 | required = Required,
37 | type = Type.ToString(),
38 | immutable = Immutable
39 | });
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/NewSt2ClientConnection.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Management.Automation;
4 | using TonyBaloney.St2.Client.Exceptions;
5 |
6 | namespace TonyBaloney.St2.Client.PowerShell
7 | {
8 | ///
9 | /// The "New-CaasConnection" Cmdlet.
10 | ///
11 | ///
12 | /// Used to create a new connection to the CaaS API.
13 | ///
14 | [Cmdlet(VerbsCommon.New, "St2ClientConnection")]
15 | [OutputType(typeof (St2ClientConnection))]
16 | public class NewSt2ClientConnectionCmdlet : PSCmdlet
17 | {
18 | ///
19 | /// The credentials used to connect to the API.
20 | ///
21 | [Parameter(Mandatory = true)]
22 | [ValidateNotNullOrEmpty]
23 | public string Username { get; set; }
24 |
25 | [Parameter(Mandatory = true)]
26 | [ValidateNotNullOrEmpty]
27 | public string Password { get; set; }
28 |
29 | ///
30 | /// Name for this connection
31 | ///
32 | [Parameter(Mandatory = false, HelpMessage = "Name to identify this connection")]
33 | public string Name { get; set; }
34 |
35 | ///
36 | /// The base uri of the REST API
37 | ///
38 | [Parameter(Mandatory = true, HelpMessage = "The URL of the API")]
39 | public string ApiUrl { get; set; }
40 |
41 | ///
42 | /// The base uri of the auth API
43 | ///
44 | [Parameter(Mandatory = true, HelpMessage = "The URL of the Auth API")]
45 | public string AuthApiUrl { get; set; }
46 |
47 | [Parameter(Mandatory = false, HelpMessage = "Ignore certificate validation errors")]
48 | public SwitchParameter IgnoreCertificateValidation { get; set; }
49 |
50 | ///
51 | /// Process the record
52 | ///
53 | protected override void ProcessRecord()
54 | {
55 | base.ProcessRecord();
56 |
57 | St2Client apiClient = new St2Client(AuthApiUrl, ApiUrl, Username, Password, IgnoreCertificateValidation.ToBool());
58 |
59 | St2ClientConnection st2ClientConnection = new St2ClientConnection(apiClient);
60 |
61 |
62 | WriteDebug("Trying to login to the REST API");
63 |
64 | try
65 | {
66 | st2ClientConnection.ApiClient.RefreshTokenAsync().Wait(TimeSpan.FromSeconds(15));
67 |
68 | if (st2ClientConnection != null)
69 | {
70 | if (!st2ClientConnection.ApiClient.HasToken())
71 | ThrowTerminatingError(new ErrorRecord(new Exception("Could not login, check credentials and access to the API"), "100", ErrorCategory.AuthenticationError, st2ClientConnection ));
72 |
73 | WriteDebug(string.Format("connection created successfully: {0}", st2ClientConnection));
74 | if (string.IsNullOrEmpty(Name))
75 | {
76 | Name = Guid.NewGuid().ToString();
77 | }
78 |
79 | if (!SessionState.GetServiceConnections().Any())
80 | WriteDebug("This is the first connection and will be the default connection.");
81 | SessionState.AddServiceConnection(Name, st2ClientConnection);
82 | if (SessionState.GetServiceConnections().Count > 1)
83 | WriteWarning(
84 | "You have created more than one connection on this session, please use the cmdlet Set-St2ActiveConnection -Name to change the active/default connection");
85 |
86 | SessionState.AddServiceConnection(Name, st2ClientConnection);
87 | WriteObject(st2ClientConnection);
88 | }
89 | }
90 | catch (FailedRequestException fre)
91 | {
92 | ThrowTerminatingError(new ErrorRecord(fre, "-1", ErrorCategory.AuthenticationError, null));
93 | }
94 | catch (AggregateException ae)
95 | {
96 | ae.Handle(
97 | e =>
98 | {
99 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.AuthenticationError, null));
100 | return true;
101 | });
102 | }
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("St2.Client.PowerShell")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("St2.Client.PowerShell")]
13 | [assembly: AssemblyCopyright("Copyright © 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("289a8947-797a-4b1b-988c-fc0c89be2566")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/RemoveActionCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Management.Automation;
3 |
4 | namespace TonyBaloney.St2.Client.PowerShell
5 | {
6 | using Action = Models.Action;
7 |
8 | [Cmdlet(VerbsCommon.Remove, "St2Action")]
9 | public class RemoveActionCmdlet
10 | : BaseClientCmdlet
11 | {
12 | [Parameter(Mandatory = true, HelpMessage = "Actions Id", ParameterSetName = "ById")] public string Id;
13 |
14 | [Parameter(Mandatory = true, HelpMessage = "Action", ParameterSetName = "ByObj")]
15 | public Action Action;
16 |
17 | protected override void ProcessRecord()
18 | {
19 | base.ProcessRecord();
20 |
21 | try
22 | {
23 | if (!String.IsNullOrWhiteSpace(Id))
24 | Connection.ApiClient.Actions.DeleteActionAsync(Id);
25 | else
26 | {
27 | Connection.ApiClient.Actions.DeleteActionAsync(Action.id);
28 | }
29 | }
30 | catch (AggregateException ae)
31 | {
32 | ae.Handle(
33 | e =>
34 | {
35 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
36 |
37 | return true;
38 | });
39 | }
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/RemoveRuleCmdlet.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Management.Automation;
3 | using TonyBaloney.St2.Client.Models;
4 |
5 | namespace TonyBaloney.St2.Client.PowerShell
6 | {
7 | [Cmdlet(VerbsCommon.Remove, "St2Rule")]
8 | public class RemoveRuleCmdlet
9 | : BaseClientCmdlet
10 | {
11 | [Parameter(Mandatory = true, HelpMessage = "Rule Id", ParameterSetName = "ById")]
12 | public string Id;
13 |
14 | [Parameter(Mandatory = true, HelpMessage = "Rule", ParameterSetName = "ByObj")]
15 | public Rule Rule;
16 |
17 | protected override void ProcessRecord()
18 | {
19 | base.ProcessRecord();
20 |
21 | try
22 | {
23 | if (!String.IsNullOrWhiteSpace(Id))
24 | Connection.ApiClient.Rules.DeleteRuleAsync(Id);
25 | else
26 | {
27 | Connection.ApiClient.Rules.DeleteRuleAsync(Rule.id);
28 | }
29 | }
30 | catch (AggregateException ae)
31 | {
32 | ae.Handle(
33 | e =>
34 | {
35 | ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
36 |
37 | return true;
38 | });
39 | }
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/SessionStateExtensions.cs:
--------------------------------------------------------------------------------
1 | // --------------------------------------------------------------------------------------------------------------------
2 | //
3 | //
4 | //
5 | //
6 | // Extension methods for working with PowerShell .
7 | //
8 | // --------------------------------------------------------------------------------------------------------------------
9 |
10 | using System;
11 | using System.Collections.Generic;
12 | using System.Linq;
13 | using System.Management.Automation;
14 |
15 | namespace TonyBaloney.St2.Client.PowerShell
16 | {
17 | ///
18 | /// Extension methods for working with PowerShell .
19 | ///
20 | ///
21 | /// TODO: Add getter / setter for default connection.
22 | ///
23 | public static class SessionStateExtensions
24 | {
25 | #region Constants
26 |
27 | ///
28 | /// Statically-cached empty list of compute service connections.
29 | ///
30 | ///
31 | /// Returned when there are no active compute service connections.
32 | ///
33 | private static readonly IReadOnlyDictionary EmptyConnectionList =
34 | new Dictionary();
35 |
36 | ///
37 | /// Variable name constants.
38 | ///
39 | public static class VariableNames
40 | {
41 | ///
42 | /// The name of the PowerShell variable in which active cloud-compute sessions are stored.
43 | ///
44 | public static readonly string ServiceSessions = "_St2ServiceComputeSessions";
45 | }
46 |
47 | #endregion // Constants
48 |
49 | ///
50 | /// The _default compute service connection name.
51 | ///
52 | private static string _defaultComputeServiceConnectionName;
53 |
54 | /// Gets service connections from session.
55 | /// Thrown when one or more required arguments are null.
56 | /// .
57 | /// The service connections from session.
58 | private static Dictionary GetServiceConnectionsFromSession(
59 | SessionState sessionState)
60 | {
61 | if (sessionState == null)
62 | throw new ArgumentNullException("sessionState");
63 |
64 | PSVariable connectionsVariable = sessionState.PSVariable.Get(VariableNames.ServiceSessions);
65 | if (connectionsVariable == null)
66 | return null;
67 |
68 | var connections = (Dictionary)connectionsVariable.Value;
69 | return connections;
70 | }
71 |
72 | /// A SessionState extension method that gets service connections.
73 | /// .
74 | /// The service connections.
75 | public static IReadOnlyDictionary GetServiceConnections(
76 | this SessionState sessionState)
77 | {
78 | Dictionary connections = GetServiceConnectionsFromSession(sessionState);
79 | if (connections == null || connections.Count == 0)
80 | return EmptyConnectionList;
81 |
82 | return connections;
83 | }
84 |
85 | /// A SessionState extension method that gets service connection by name.
86 | /// Thrown when one or more required arguments are null.
87 | /// .
88 | /// The name.
89 | /// The service connection by name.
90 | public static St2ClientConnection GetServiceConnectionByName(this SessionState sessionState, string name)
91 | {
92 | if (string.IsNullOrEmpty(name))
93 | throw new ArgumentNullException("name");
94 |
95 | Dictionary connections = GetServiceConnectionsFromSession(sessionState);
96 | if (connections == null || connections.Count == 0)
97 | return null;
98 | if (connections.ContainsKey(name))
99 | return connections[name];
100 |
101 | return null;
102 | }
103 |
104 | /// A SessionState extension method that gets default service connection.
105 | /// .
106 | /// The default service connection.
107 | public static St2ClientConnection GetDefaultServiceConnection(this SessionState sessionState)
108 | {
109 | Dictionary connections = GetServiceConnectionsFromSession(sessionState);
110 | if (connections == null)
111 | return null;
112 |
113 | if (!connections.ContainsKey(_defaultComputeServiceConnectionName))
114 | return null;
115 |
116 | return connections[_defaultComputeServiceConnectionName];
117 | }
118 |
119 | /// A SessionState extension method that sets default service connection.
120 | /// Thrown when the index is outside the required
121 | /// range.
122 | /// .
123 | /// The connection Name.
124 | public static void SetDefaultServiceConnection(this SessionState sessionState, string connectionName)
125 | {
126 | Dictionary connections = GetServiceConnectionsFromSession(sessionState);
127 | if (!connections.ContainsKey(connectionName))
128 | throw new IndexOutOfRangeException("connectionName does not exisits");
129 | _defaultComputeServiceConnectionName = connectionName;
130 | }
131 |
132 | /// A SessionState extension method that adds a service connection.
133 | /// Thrown when one or more required arguments are null.
134 | /// .
135 | /// The connection Name.
136 | /// The connection.
137 | /// A St2ClientConnection.
138 | public static St2ClientConnection AddServiceConnection(this SessionState sessionState,
139 | string connectionName, St2ClientConnection connection)
140 | {
141 | if (sessionState == null)
142 | throw new ArgumentNullException("sessionState");
143 |
144 | if (connection == null)
145 | throw new ArgumentNullException("connection");
146 |
147 |
148 | if (string.IsNullOrEmpty(connectionName))
149 | throw new ArgumentNullException("connectionName");
150 |
151 |
152 | Dictionary connections;
153 | PSVariable connectionsVariable = sessionState.PSVariable.Get(VariableNames.ServiceSessions);
154 | if (connectionsVariable == null)
155 | {
156 | connectionsVariable = new PSVariable(
157 | VariableNames.ServiceSessions, connections = new Dictionary(),
158 | ScopedItemOptions.AllScope
159 | );
160 | sessionState.PSVariable.Set(connectionsVariable);
161 | }
162 | else
163 | {
164 | connections = (Dictionary)connectionsVariable.Value;
165 | if (connections == null)
166 | {
167 | connectionsVariable.Value = connections = new Dictionary();
168 | sessionState.PSVariable.Set(connectionsVariable);
169 | }
170 | }
171 |
172 | if (!connections.ContainsKey(connectionName))
173 | connections.Add(connectionName, connection);
174 | else
175 | connections[connectionName] = connection;
176 |
177 | if (string.IsNullOrEmpty(_defaultComputeServiceConnectionName) || connections.Count().Equals(1))
178 | _defaultComputeServiceConnectionName = connectionName;
179 |
180 | return connection;
181 | }
182 |
183 | /// A SessionState extension method that removes the service connection.
184 | /// Thrown when one or more required arguments are null.
185 | /// .
186 | /// The connection Name.
187 | /// true if it succeeds, false if it fails.
188 | public static bool RemoveServiceConnection(this SessionState sessionState, string connectionName)
189 | {
190 | if (sessionState == null)
191 | throw new ArgumentNullException("sessionState");
192 |
193 | if (string.IsNullOrEmpty(connectionName))
194 | throw new ArgumentNullException("connectionName");
195 |
196 | PSVariable connectionsVariable = sessionState.PSVariable.Get(VariableNames.ServiceSessions);
197 | if (connectionsVariable == null)
198 | return false;
199 |
200 | var connections = (Dictionary)connectionsVariable.Value;
201 | if (connections == null)
202 | return false;
203 |
204 | return connections.Remove(connectionName);
205 | }
206 | }
207 | }
--------------------------------------------------------------------------------
/St2.Client.PowerShell/St2.Client.PowerShell.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {4B6DEAC5-2B3B-4E30-B538-AD7ECD96DCCF}
8 | Library
9 | Properties
10 | TonyBaloney.St2.Client.PowerShell
11 | St2.Client.PowerShell
12 | v4.5
13 | 512
14 |
15 |
16 |
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 | false
25 | ..\..\DimensionData.ComputeClient\CaaS_PS.ruleset
26 |
27 |
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 | false
35 |
36 |
37 |
38 |
39 |
40 | False
41 | ..\..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | {1c36dc71-36d3-4e2f-978d-7f6b2cc3d3ab}
69 | St2.Client
70 |
71 |
72 |
73 |
74 | Always
75 |
76 |
77 | Always
78 |
79 |
80 |
81 |
82 |
83 | Designer
84 |
85 |
86 |
87 |
94 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/St2.Client.PowerShell.csproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Program
5 | C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
6 | -noexit -command "&{ import-module .\St2.Client.PowerShell.dll -verbose}"
7 |
8 |
9 | ShowAllFiles
10 |
11 |
12 | -noexit -command "&{ import-module .\St2.Client.PowerShell.dll -verbose}"
13 | Program
14 | C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
15 |
16 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/St2.Client.PowerShell.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | St2.Client.PowerShell
5 | $version$
6 | StackStorm API PowerShell module
7 | Anthony Shaw
8 | https://github.com/tonybaloney/St2Client
9 | false
10 | Provides a client to talk to a StackStorm API via PowerShell.
11 | Provides a client to talk to a StackStorm API.
12 | .
13 | Copyright Dimension Data 2015
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/St2.Client.PowerShell/St2.Client.psd1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tonybaloney/St2Client/6d6fa592bbb444aed3711a1fdf0633bcec8d62c3/St2.Client.PowerShell/St2.Client.psd1
--------------------------------------------------------------------------------
/St2.Client.PowerShell/St2ClientConnection.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace TonyBaloney.St2.Client.PowerShell
4 | {
5 | public sealed class St2ClientConnection
6 | : IDisposable
7 | {
8 | public St2ClientConnection(ISt2Client apiClient)
9 | {
10 | if (apiClient == null)
11 | throw new ArgumentNullException("apiClient");
12 |
13 | ApiClient = apiClient;
14 | }
15 |
16 | ///
17 | /// The API client represented by the connection.
18 | ///
19 | internal ISt2Client ApiClient { get; private set; }
20 |
21 | ///
22 | /// Dispose of resources being used by the CaaS API connection.
23 | ///
24 | public void Dispose()
25 | {
26 | if (ApiClient != null)
27 | {
28 | ApiClient.Dispose();
29 | ApiClient = null;
30 | }
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/St2.Client.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.31101.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "St2.Client", "St2.Client\St2.Client.csproj", "{1C36DC71-36D3-4E2F-978D-7F6B2CC3D3AB}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "St2.Client.PowerShell", "St2.Client.PowerShell\St2.Client.PowerShell.csproj", "{4B6DEAC5-2B3B-4E30-B538-AD7ECD96DCCF}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {1C36DC71-36D3-4E2F-978D-7F6B2CC3D3AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {1C36DC71-36D3-4E2F-978D-7F6B2CC3D3AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {1C36DC71-36D3-4E2F-978D-7F6B2CC3D3AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {1C36DC71-36D3-4E2F-978D-7F6B2CC3D3AB}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {4B6DEAC5-2B3B-4E30-B538-AD7ECD96DCCF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {4B6DEAC5-2B3B-4E30-B538-AD7ECD96DCCF}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {4B6DEAC5-2B3B-4E30-B538-AD7ECD96DCCF}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {4B6DEAC5-2B3B-4E30-B538-AD7ECD96DCCF}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | EndGlobal
29 |
--------------------------------------------------------------------------------
/St2.Client/Apis/ActionsApi.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading.Tasks;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.Apis
7 | {
8 | using Action = Models.Action;
9 |
10 | /// The actions api.
11 | public class ActionsApi : IActionsApi
12 | {
13 | private ISt2Client _host;
14 |
15 | ///
16 | /// Initializes a new instance of the TonyBaloney.St2.Client.Apis.ActionsApi class.
17 | ///
18 | /// Thrown when one or more required arguments are null.
19 | /// The host.
20 | public ActionsApi(ISt2Client host)
21 | {
22 | if (host == null)
23 | throw new ArgumentNullException("host");
24 | _host = host;
25 | }
26 |
27 | /// Get all available Actions.
28 | /// A List of Actions.
29 | ///
30 | public async Task> GetActionsAsync()
31 | {
32 | return await _host.GetApiRequestAsync>("/v1/actions");
33 | }
34 |
35 | /// Gets actions for pack.
36 | /// The pack name.
37 | /// A List of Actions.
38 | ///
39 | public async Task> GetActionsForPackAsync(string pack)
40 | {
41 | return await _host.GetApiRequestAsync>("/v1/actions?pack=" + pack);
42 | }
43 |
44 | public async Task> GetActionsForPackByNameAsync(string pack, string name)
45 | {
46 | return await _host.GetApiRequestAsync>("/v1/actions?pack=" + pack + "&name=" + name);
47 | }
48 |
49 | /// Gets actions by name.
50 | /// The action name.
51 | /// A List of Actions.
52 | ///
53 | public async Task> GetActionsByNameAsync(string name)
54 | {
55 | return await _host.GetApiRequestAsync>("/v1/actions?name=" + name);
56 | }
57 |
58 | /// Deletes the action described by actionId.
59 | /// can be either the ID (e.g. 1 or the ref e.g. mypack.myaction).
60 | ///
61 | public async Task DeleteActionAsync(string actionId)
62 | {
63 | await _host.DeleteApiRequestAsync("/v1/actions/" + actionId);
64 | }
65 |
66 | /// Creates a new action.
67 | /// The to create.
68 | /// The new action asynchronous.
69 | ///
70 | public async Task CreateActionAsync(CreateAction action)
71 | {
72 | return await _host.PostApiRequestAsync("/v1/actions/", action);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/St2.Client/Apis/ExecutionsApi.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading.Tasks;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.Apis
7 | {
8 | /// The executions API.
9 | ///
10 | public class ExecutionsApi : IExecutionsApi
11 | {
12 | private ISt2Client _host;
13 |
14 | ///
15 | /// Initializes a new instance of the TonyBaloney.St2.Client.Apis.ExecutionsApi class.
16 | ///
17 | /// Thrown when one or more required arguments are null.
18 | /// The host.
19 | public ExecutionsApi(ISt2Client host)
20 | {
21 | if (host == null)
22 | throw new ArgumentNullException("host");
23 | _host = host;
24 | }
25 |
26 | /// Gets execution.
27 | /// The identifier.
28 | /// The execution.
29 | ///
30 | public async Task GetExecutionAsync(string id)
31 | {
32 | return await _host.GetApiRequestAsync("/v1/executions/"+id);
33 | }
34 |
35 | /// Gets a list of executions.
36 | /// The number of items to return (default 5).
37 | /// A list of .
38 | ///
39 | public async Task> GetExecutionsAsync(int limit = 5)
40 | {
41 | return await _host.GetApiRequestAsync>("/v1/executions?limit="+limit);
42 | }
43 |
44 | /// Gets executions for action.
45 | /// Name of the action.
46 | /// The number of items to return (default 5).
47 | /// A list of .
48 | ///
49 | public async Task> GetExecutionsForActionAsync(string actionName, int limit = 5)
50 | {
51 | return await _host.GetApiRequestAsync>("/v1/executions?action="+actionName +"&limit="+limit);
52 | }
53 |
54 | /// Executes the action.
55 | /// Name of the action.
56 | /// The parameters for the given action.
57 | /// The resulting execution;
58 | ///
59 | public async Task ExecuteActionAsync(string actionName, Dictionary parameters)
60 | {
61 | ExecuteActionRequest request = new ExecuteActionRequest
62 | {
63 | action = actionName,
64 | parameters = parameters
65 | };
66 | return await _host.PostApiRequestAsync("/v1/executions/", request);
67 | }
68 |
69 | /// Executes the action.
70 | /// Name of the action.
71 | /// The parameters for the given action.
72 | /// The resulting execution;
73 | ///
74 | public async Task ExecuteActionAsync(string actionName, Dictionary parameters)
75 | {
76 | ExecuteComplexActionRequest request = new ExecuteComplexActionRequest
77 | {
78 | action = actionName,
79 | parameters = parameters
80 | };
81 | return await _host.PostApiRequestAsync("/v1/executions/", request);
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/St2.Client/Apis/IActionsApi.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Threading.Tasks;
3 | using TonyBaloney.St2.Client.Models;
4 |
5 | namespace TonyBaloney.St2.Client.Apis
6 | {
7 | using Action = Models.Action;
8 |
9 | /// Interface for actions API.
10 | public interface IActionsApi
11 | {
12 | /// Get all available Actions.
13 | /// A List of .
14 | Task> GetActionsAsync();
15 |
16 | /// Gets actions for pack.
17 | /// The pack name.
18 | /// A List of .
19 | Task> GetActionsForPackAsync(string pack);
20 |
21 | Task> GetActionsForPackByNameAsync(string pack, string name);
22 |
23 | /// Gets actions by name.
24 | /// The action name.
25 | /// A List of .
26 | Task> GetActionsByNameAsync(string name);
27 |
28 | /// Deletes the action described by actionId.
29 | /// can be either the ID (e.g. 1 or the ref e.g. mypack.myaction).
30 | Task DeleteActionAsync(string actionId);
31 |
32 | /// Creates a new action.
33 | /// The to create.
34 | Task CreateActionAsync(CreateAction action);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/St2.Client/Apis/IExecutionsApi.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Threading.Tasks;
3 | using TonyBaloney.St2.Client.Models;
4 |
5 | namespace TonyBaloney.St2.Client.Apis
6 | {
7 | /// Interface for executions API.
8 | public interface IExecutionsApi
9 | {
10 | /// Gets execution.
11 | /// The identifier.
12 | /// The execution.
13 | Task GetExecutionAsync(string id);
14 |
15 | /// Gets a list of executions.
16 | /// The number of items to return (default 5).
17 | /// A list of .
18 | Task> GetExecutionsAsync(int limit=5);
19 |
20 | /// Gets executions for action.
21 | /// Name of the action.
22 | /// The number of items to return (default 5).
23 | /// A list of .
24 | Task> GetExecutionsForActionAsync(string actionName, int limit=5);
25 |
26 | /// Executes the action.
27 | /// Name of the action.
28 | /// The parameters for the given action.
29 | /// The resulting execution;
30 | Task ExecuteActionAsync(string actionName, Dictionary parameters);
31 |
32 | /// Executes the action.
33 | /// Name of the action.
34 | /// The parameters for the given action.
35 | /// The resulting execution;
36 | Task ExecuteActionAsync(string actionName, Dictionary parameters);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/St2.Client/Apis/IPacksApi.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Threading.Tasks;
3 | using TonyBaloney.St2.Client.Models;
4 |
5 | namespace TonyBaloney.St2.Client.Apis
6 | {
7 | /// Interface for packs API.
8 | public interface IPacksApi
9 | {
10 | /// Get a list of packs.
11 | /// A List of .
12 | Task> GetPacksAsync();
13 |
14 | /// Gets packs by name.
15 | /// Name of the pack.
16 | /// A List of .
17 | Task> GetPacksByNameAsync(string packName);
18 |
19 | /// Gets packs by identifier.
20 | /// Identifier for the pack.
21 | /// A List of .
22 | Task> GetPacksByIdAsync(string packId);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/St2.Client/Apis/IRulesApi.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Threading.Tasks;
3 | using TonyBaloney.St2.Client.Models;
4 |
5 | namespace TonyBaloney.St2.Client.Apis
6 | {
7 | /// Interface for rules API.
8 | public interface IRulesApi
9 | {
10 | /// Gets rules.
11 | /// The rules.
12 | Task> GetRulesAsync();
13 |
14 | /// Gets rules for pack.
15 | /// Name of the pack.
16 | /// The rules for pack.
17 | Task> GetRulesForPackAsync(string packName);
18 |
19 | /// Gets rules by name.
20 | /// The name.
21 | /// The rules by name.
22 | Task> GetRulesByNameAsync(string name);
23 |
24 | /// Deletes the rule described by ruleId.
25 | /// Identifier for the rule.
26 | /// A Task.
27 | Task DeleteRuleAsync(string ruleId);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/St2.Client/Apis/PacksApi.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading.Tasks;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.Apis
7 | {
8 | /// The packs api.
9 | ///
10 | public class PacksApi : IPacksApi
11 | {
12 | private ISt2Client _host;
13 |
14 | ///
15 | /// Initializes a new instance of the TonyBaloney.St2.Client.Apis.PacksApi class.
16 | ///
17 | /// Thrown when one or more required arguments are null.
18 | /// The host.
19 | public PacksApi(ISt2Client host)
20 | {
21 | if (host == null)
22 | throw new ArgumentNullException("host");
23 | _host = host;
24 | }
25 |
26 | /// Get a list of packs.
27 | /// A List of .
28 | ///
29 | public async Task> GetPacksAsync()
30 | {
31 | return await _host.GetApiRequestAsync>("/v1/packs");
32 | }
33 |
34 | /// Gets packs by name.
35 | /// Name of the pack.
36 | /// A List of .
37 | ///
38 | public async Task> GetPacksByNameAsync(string packName)
39 | {
40 | return await _host.GetApiRequestAsync>("/v1/packs?name=" + packName);
41 | }
42 |
43 | /// Gets packs by identifier.
44 | /// Identifier for the pack.
45 | /// A List of .
46 | ///
47 | public async Task> GetPacksByIdAsync(string packId)
48 | {
49 | return await _host.GetApiRequestAsync>("/v1/packs?ref=" + packId);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/St2.Client/Apis/RulesApi.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading.Tasks;
4 | using TonyBaloney.St2.Client.Models;
5 |
6 | namespace TonyBaloney.St2.Client.Apis
7 | {
8 | /// The rules api.
9 | ///
10 | public class RulesApi :
11 | IRulesApi
12 | {
13 | /// The host process.
14 | private ISt2Client _host;
15 |
16 | ///
17 | /// Initializes a new instance of the TonyBaloney.St2.Client.Apis.RulesApi class.
18 | ///
19 | /// Thrown when one or more required arguments are null.
20 | /// The host.
21 | public RulesApi(ISt2Client host)
22 | {
23 | if (host == null)
24 | throw new ArgumentNullException("host");
25 | _host = host;
26 | }
27 |
28 | /// Gets rules .
29 | /// The rules .
30 | public async Task> GetRulesAsync()
31 | {
32 | return await _host.GetApiRequestAsync>("/v1/rules/");
33 | }
34 |
35 | /// Gets rules for pack .
36 | /// Name of the pack.
37 | /// The rules for pack .
38 | public async Task> GetRulesForPackAsync(string packName)
39 | {
40 | return await _host.GetApiRequestAsync>("/v1/rules?pack=" + packName);
41 | }
42 |
43 | /// Gets rules by name .
44 | /// The rule name.
45 | /// The rules by name .
46 | public async Task> GetRulesByNameAsync(string name)
47 | {
48 | return await _host.GetApiRequestAsync>("/v1/rules?name=" + name);
49 | }
50 |
51 | /// Deletes the rule described by ruleId.
52 | /// Identifier for the rule.
53 | /// A Task.
54 | ///
55 | public async Task DeleteRuleAsync(string ruleId)
56 | {
57 | await _host.DeleteApiRequestAsync("/v1/rules/" + ruleId);
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/St2.Client/AuthExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Net.Http;
2 | using TonyBaloney.St2.Client.Exceptions;
3 | using TonyBaloney.St2.Client.Models;
4 |
5 | namespace TonyBaloney.St2.Client
6 | {
7 | /// An authentication extensions.
8 | public static class AuthExtensions
9 | {
10 | ///
11 | /// A HttpClient extension method that adds an x-auth-token to the client headers
12 | ///
13 | /// The client to act on.
14 | /// The token.
15 | public static void AddXAuthToken(this HttpClient client, TokenResponse token)
16 | {
17 | if (token == null)
18 | throw new InvalidTokenException("Please login first, or could not find a login token.");
19 |
20 | client.DefaultRequestHeaders.Add("x-auth-token", token.token);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/St2.Client/Exceptions/ExceptionFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.Http;
3 |
4 | namespace TonyBaloney.St2.Client.Exceptions
5 | {
6 | public static class ExceptionFactory
7 | {
8 | public static FailedRequestException FailedPostRequest(HttpResponseMessage response)
9 | {
10 | return new FailedRequestException("POST Request failed", response.RequestMessage.RequestUri, response.StatusCode, (response.Content != null ? response.Content.ToString() : ""));
11 | }
12 |
13 | public static FailedRequestException FailedGetRequest(HttpResponseMessage response)
14 | {
15 | return new FailedRequestException("GET Request failed", response.RequestMessage.RequestUri, response.StatusCode, (response.Content != null ? response.Content.ToString() : ""));
16 | }
17 |
18 | public static FailedRequestException FailedTokenException(HttpResponseMessage response)
19 | {
20 | return new FailedRequestException("Token Auth Request failed", response.RequestMessage.RequestUri, response.StatusCode, (response.Content != null ? response.Content.ToString() : ""));
21 | }
22 |
23 | public static FailedRequestException FailedDeleteRequest(HttpResponseMessage response)
24 | {
25 | return new FailedRequestException("DELETE Request failed", response.RequestMessage.RequestUri, response.StatusCode, (response.Content != null ? response.Content.ToString() : ""));
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/St2.Client/Exceptions/FailedRequestException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net;
3 |
4 | namespace TonyBaloney.St2.Client.Exceptions
5 | {
6 | /// Exception for signalling failed request errors.
7 | ///
8 | public class FailedRequestException
9 | : Exception
10 | {
11 | public string FailureMessage;
12 |
13 | public Uri RequestUri;
14 |
15 | public HttpStatusCode StatusCode;
16 |
17 | public string ResponseMessage;
18 |
19 | ///
20 | /// Initializes a new instance of the
21 | /// TonyBaloney.St2.Client.Exceptions.FailedRequestException class.
22 | ///
23 | /// The message.
24 | public FailedRequestException(string message) :
25 | base(message)
26 | {
27 | }
28 |
29 | ///
30 | /// Initializes a new instance of the
31 | /// FailedRequestException class.
32 | ///
33 | /// Message describing the failure.
34 | /// URI of the request.
35 | /// The status code.
36 | /// Message describing the response.
37 | public FailedRequestException(string failureMessage, Uri requestUri, HttpStatusCode statusCode, string responseMessage)
38 | : base(String.Format("{3}, Request to {0} failed with status '{1}', response was {2}", requestUri, statusCode,
39 | responseMessage, failureMessage))
40 | {
41 | FailureMessage = failureMessage;
42 | RequestUri = requestUri;
43 | StatusCode = statusCode;
44 | ResponseMessage = responseMessage;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/St2.Client/Exceptions/InvalidTokenException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace TonyBaloney.St2.Client.Exceptions
4 | {
5 | /// Exception for signalling invalid token errors.
6 | ///
7 | public class InvalidTokenException
8 | : Exception
9 | {
10 | ///
11 | /// Initializes a new instance of the TonyBaloney.St2.Client.Exceptions.InvalidTokenException
12 | /// class.
13 | ///
14 | /// The message.
15 | public InvalidTokenException(string message) :
16 | base(message)
17 | {
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/St2.Client/ISt2Client.cs:
--------------------------------------------------------------------------------
1 | using System.Threading.Tasks;
2 | using TonyBaloney.St2.Client.Apis;
3 |
4 | namespace TonyBaloney.St2.Client
5 | {
6 | /// Interface for StackStorm API client.
7 | public interface ISt2Client
8 | {
9 | /// Refresh the auth token.
10 | Task RefreshTokenAsync();
11 |
12 | /// Make an asynchronous GET request to the API.
13 | /// Expected Type of the response.
14 | /// URL of the GET request.
15 | /// The Typed response.
16 | Task GetApiRequestAsync(string url);
17 |
18 | /// Make an asynchronous POST request to the API.
19 | /// Expected Type of the response.
20 | /// Expected Type of of the request message.
21 | /// URL of the POST request.
22 | /// The request.
23 | /// The Typed response.
24 | Task PostApiRequestAsync(string url, TRequestType request);
25 |
26 | /// Make a DELETE request to the API.
27 | /// URL of the request.
28 | Task DeleteApiRequestAsync(string url);
29 |
30 | /// Accessor for the Actions related methods
31 | /// The actions accessor.
32 | IActionsApi Actions { get; }
33 |
34 | /// Accessor for the Packs related methods.
35 | /// The Packs accessor.
36 | IPacksApi Packs { get; }
37 |
38 | /// Accessor for the Executions related methods.
39 | /// The Executions accessor.
40 | IExecutionsApi Executions { get; }
41 |
42 | /// Accessor for the Rules related methods.
43 | /// The Rules accessor.
44 | IRulesApi Rules { get; }
45 |
46 | void Dispose();
47 |
48 | /// Query if this object has a token.
49 | /// true if token, false if not.
50 | bool HasToken();
51 | }
52 | }
--------------------------------------------------------------------------------
/St2.Client/Models/Action.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace TonyBaloney.St2.Client.Models
4 | {
5 | public class Action
6 | {
7 | public string description { get; set; }
8 | public string runner_type { get; set; }
9 | public bool enabled { get; set; }
10 | public string pack { get; set; }
11 | public string entry_point { get; set; }
12 | public string uid { get; set; }
13 | public Dictionary parameters { get; set; }
14 | public string @ref { get; set; }
15 | public string id { get; set; }
16 | public string name { get; set; }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/St2.Client/Models/ActionParameter.cs:
--------------------------------------------------------------------------------
1 | namespace TonyBaloney.St2.Client.Models
2 | {
3 | public class ActionParameter
4 | {
5 | public string type;
6 | public string description;
7 | public object @default;
8 | public bool required;
9 | public int order;
10 | public bool immutable=false;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/St2.Client/Models/CreateAction.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace TonyBaloney.St2.Client.Models
4 | {
5 | public class CreateAction
6 | {
7 | public string description { get; set; }
8 | public string runner_type { get; set; }
9 | public bool enabled { get; set; }
10 | public string pack { get; set; }
11 | public string entry_point { get; set; }
12 | public Dictionary parameters { get; set; }
13 | public string name { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/St2.Client/Models/ExecuteActionRequest.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace TonyBaloney.St2.Client.Models
4 | {
5 | public class ExecuteActionRequest
6 | {
7 | public string action;
8 | public Dictionary parameters;
9 | }
10 |
11 | public class ExecuteComplexActionRequest
12 | {
13 | public string action;
14 | public Dictionary parameters;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/St2.Client/Models/Execution.cs:
--------------------------------------------------------------------------------
1 | namespace TonyBaloney.St2.Client.Models
2 | {
3 | public class Execution
4 | {
5 | public string status { get; set; }
6 | public string start_timestamp { get; set; }
7 | public TriggerType trigger_type { get; set; }
8 | public Runner runner { get; set; }
9 | public Rule rule { get; set; }
10 | public Trigger trigger { get; set; }
11 | public ExecutionContext context { get; set; }
12 | public Action action { get; set; }
13 | public string id { get; set; }
14 | public string end_timestamp { get; set; }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/St2.Client/Models/ExecutionContext.cs:
--------------------------------------------------------------------------------
1 | namespace TonyBaloney.St2.Client.Models
2 | {
3 | public class ExecutionContext
4 | {
5 | public TriggerInstance trigger_instance { get; set; }
6 | public Rule rule { get; set; }
7 | public string user { get; set; }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/St2.Client/Models/NamedActionParameter.cs:
--------------------------------------------------------------------------------
1 | namespace TonyBaloney.St2.Client.Models
2 | {
3 | public class NamedActionParameter
4 | : ActionParameter
5 | {
6 | public string name;
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/St2.Client/Models/Pack.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace TonyBaloney.St2.Client.Models
4 | {
5 | public class Pack
6 | {
7 | public List files { get; set; }
8 | public string description { get; set; }
9 | public string name { get; set; }
10 | public string author { get; set; }
11 | public string id { get; set; }
12 | public string version { get; set; }
13 | public List keywords { get; set; }
14 | public string @ref { get; set; }
15 | public string email { get; set; }
16 | public string uid { get; set; }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/St2.Client/Models/ParameterType.cs:
--------------------------------------------------------------------------------
1 | namespace TonyBaloney.St2.Client.Models
2 | {
3 | public enum ParameterType
4 | {
5 | @string,
6 | @int,
7 | @bool
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/St2.Client/Models/PayloadSchema.cs:
--------------------------------------------------------------------------------
1 | namespace TonyBaloney.St2.Client.Models
2 | {
3 | public class PayloadSchema
4 | {
5 | public string type { get; set; }
6 | public dynamic properties { get; set; }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/St2.Client/Models/Rule.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace TonyBaloney.St2.Client.Models
4 | {
5 | public class Rule
6 | {
7 | public string uid { get; set; }
8 | public List