-
Notifications
You must be signed in to change notification settings - Fork 41
/
StoreIngestionApi.psm1
1849 lines (1515 loc) · 74.8 KB
/
StoreIngestionApi.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) Microsoft Corporation. All rights reserved.
# Configured via Set-StoreBrokerAuthentication / Clear-StoreBrokerAuthentication
$script:proxyEndpoint = $null
# We are defining these as script variables here to enable the caching of the
# authentication credential for the current PowerShell session.
[string]$script:authTenantId = $null
[PSCredential]$script:authCredential = $null
[string]$script:authTenantName = $null
# By default, ConvertTo-Json won't expand nested objects further than a depth of 2
# We always want to expand as deep as possible, so set this to a much higher depth
# than the actual depth
$script:jsonConversionDepth = 20
# The number of seconds that we'll buffer from the expected AccessToken expiration
# to allow for time lost during network communication.
$script:accessTokenRefreshBufferSeconds = 90
# The number of seconds that we'll allow to pass before assuming that the AccessToken
# has expired and needs to be refreshed. We'll update this value whenever we really
# do get an AccessToken so that it accurately reflects the time a token can last.
$script:accessTokenTimeoutSeconds = (59 * 60) - $script:accessTokenRefreshBufferSeconds
# Common keywords in the API Model used by StoreBroker
$script:keywordSpecificDate = 'SpecificDate'
$script:keywordManual = 'Manual'
$script:keywordDefault = 'Default'
$script:keywordNoAction = 'NoAction'
$script:keywordPendingDelete = 'PendingDelete'
$script:keywordPendingCommit = 'PendingCommit'
$script:keywordRelease = 'Release'
$script:keywordPublished = 'Published'
# Warning that is referenced in multiple places throughout the module.
# {0} will be replaced in context with the relevant command.
$script:manualPublishWarning = @"
PLEASE NOTE: Due to the nature of how the Store API works, you won't see any of your changes in the
Dev Portal until your submission has entered into certification. It doesn't have to *complete*
certification for you to see your changes, but it does have to enter certification first.
If it's important for you to verify your changes in the Dev Portal prior to publishing,
consider publishing with the `"$script:keywordManual`" targetPublishMode by setting that value in your
config file and then additionally specifying the -UpdatePublishModeAndVisibility switch
when calling {0}, or by specifying the
-TargetPublishMode $script:keywordManual parameter when calling {0}.
"@
function Initialize-StoreIngestionApiGlobalVariables
{
<#
.SYNOPSIS
Initializes the global variables that are "owned" by the StoreIngestionApi script file.
.DESCRIPTION
Initializes the global variables that are "owned" by the StoreIngestionApi script file.
Global variables are used sparingly to enables users a way to control certain extensibility
points with this module.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.NOTES
Internal-only helper method.
The only reason this exists is so that we can leverage CodeAnalysis.SuppressMessageAttribute,
which can only be applied to functions. Otherwise, we would have just had the relevant
initialization code directly above the function that references the variable.
We call this immediately after the declaration so that the variables are available for
reference in any function below.
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We use global variables sparingly and intentionally for module configuration, and employ a consistent naming convention.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="This is where we would initialize any global variables for this script.")]
param()
# We only set their values if they don't already have values defined.
# We use -ErrorAction SilentlyContinue during the Get-Variable check since it throws an exception
# by default if the variable we're getting doesn't exist, and we just want the bool result.
if (!(Get-Variable -Name SBDefaultProxyEndpoint -Scope Global -ValueOnly -ErrorAction SilentlyContinue))
{
$global:SBDefaultProxyEndpoint = $null
}
}
# We need to be sure to call this explicitly so that the global variables get initialized.
Initialize-StoreIngestionApiGlobalVariables
function Set-StoreBrokerAuthentication
{
<#
.SYNOPSIS
Prompts the user for their client id and secret so that they can be cached for
this PowerShell session to avoid repeated prompts.
.DESCRIPTION
Prompts the user for their client id and secret so that they can be cached for
this PowerShell session to avoid repeated prompts.
The cached credential can always be cleared by calling Clear-StoreBrokerAuthentication.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER TenantId
The Azure Active Directory Tenant ID that authentication must go through.
.PARAMETER Credential
Optional parameter that allows you to pass-in the credential object to be used, as
opposed to having this command pop-up a UI for the user to manually enter in
their credentials.
.PARAMETER OnlyCacheTenantId
Normally, calling this cmdlet will result in an authentication prompt to retrieve
the clientId and clientSecret needed for authentication (unless Credential is provided).
If this switch is specified that prompt will be suppressed so that all that will occur
is the caching of the TenantId. This will not cause previously cached credentials to
be cleared however (to do that, use Clear-StoreBrokerAuthentication)
.PARAMETER UseProxy
If specified, authentication will occur via a proxy server as opposed to authenticating
with a standard TenantId/ClientId/ClientSecret combination. Users have the option of
additionally specifying a value for ProxyEndpoint if they wish to use a non-default
proxy server.
.PARAMETER ProxyEndpoint
The REST endpoint that will be used to authenticate user requests and then proxy those
requests to the real Store REST API endpoint.
.PARAMETER TenantName
The friendly name for the tenant that can be used with a Proxy that supports multiple
tenants.
.EXAMPLE
Set-StoreBrokerAuthentication "abcdef01-2345-6789-0abc-def123456789"
Caches the tenantId as "abcdef01-2345-6789-0abc-def123456789" for the duration of the
PowerShell session. Prompts the user for the client id and secret.
These values will be cached for the duration of this PowerShell session.
They can be cleared by calling Clear-StoreBrokerAuthentication.
.EXAMPLE
Set-StoreBrokerAuthentication "abcdef01-2345-6789-0abc-def123456789" $cred
Caches the provided tenantId and credential without any prompting to the user.
This is helpful when you want to run the script without any user interaction.
These values will be cached for the duration of this PowerShell session.
They can be cleared by calling Clear-StoreBrokerAuthentication.
For assistance in learning how to manually create $cred, refer to:
https://technet.microsoft.com/en-us/magazine/ff714574.aspx
.EXAMPLE
Set-StoreBrokerAuthentication "abcdef01-2345-6789-0abc-def123456789" -OnlyCacheTenantId
Caches the tenantId as "abcdef01-2345-6789-0abc-def123456789" for the duration of the
PowerShell session, but does not prompt the user to enter the clientId/clientSecret
credential values.
.EXAMPLE
Set-StoreBrokerAuthentication -UseProxy
Bypasses normal authentication and tells StoreBroker to use the dafault proxy server
endpoint for authentication instead.
#>
[CmdletBinding(
SupportsShouldProcess,
DefaultParametersetName="NoCred")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We use global variables sparingly and intentionally for module configuration, and employ a consistent naming convention.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUsePSCredentialType", "", Justification="The System.Management.Automation.Credential() attribute does not appear to work in PowerShell v4 which we need to support.")]
param(
[Parameter(
Mandatory,
ParameterSetName="NoCred",
Position=0)]
[Parameter(
Mandatory,
ParameterSetName="WithCred",
Position=0)]
[Parameter(
ParameterSetName="Proxy",
Position=2)]
[string] $TenantId,
[Parameter(
ParameterSetName="WithCred",
Position=1)]
[PSCredential] $Credential = $null,
[Parameter(ParameterSetName="NoCred")]
[switch] $OnlyCacheTenantId,
[Parameter(
Mandatory,
ParameterSetName="Proxy",
Position=0)]
[switch] $UseProxy,
[Parameter(
ParameterSetName="Proxy",
Position=1)]
[string] $ProxyEndpoint = $global:SBDefaultProxyEndpoint,
[Parameter(
ParameterSetName="Proxy",
Position=2)]
[string] $TenantName = $null
)
Write-Log "Executing: $($MyInvocation.Line)" -Level Verbose
if ($UseProxy)
{
if ((-not [String]::IsNullOrWhiteSpace($TenantId)) -and (-not [String]::IsNullOrWhiteSpace($TenantName)))
{
$message = "You cannot set both TenantId and TenantName. Only provide one of them."
Write-Log $message -Level Error
throw $message
}
if ($null -ne $script:authCredential)
{
Write-Log "Your cached credentials will no longer be used since you have enabled Proxy usage." -Level Warning
}
if ($ProxyEndpoint.EndsWith('/') -or $ProxyEndpoint.EndsWith('\'))
{
$ProxyEndpoint = $ProxyEndpoint.Substring(0, $ProxyEndpoint.Length - 1)
}
$script:proxyEndpoint = $ProxyEndpoint
if ((-not [String]::IsNullOrWhiteSpace($TenantId)) -and
$PSCmdlet.ShouldProcess($TenantId, "Cache tenantId"))
{
$script:authTenantId = $TenantId
$script:authTenantName = $null
}
if ((-not [String]::IsNullOrWhiteSpace($TenantName)) -and
$PSCmdlet.ShouldProcess($TenantName, "Cache tenantName"))
{
$script:authTenantId = $null
$script:authTenantName = $TenantName
}
return
}
if ($PSCmdlet.ShouldProcess($TenantId, "Cache tenantId"))
{
$script:authTenantId = $TenantId
$script:authTenantName = $null
}
# By calling into here with any other parameter set, the user is indicating that the proxy
# should no longer be used, so we must clear out any existing value.
$script:proxyEndpoint = $null
if (($null -eq $Credential) -and (-not $OnlyCacheTenantId))
{
if ($PSCmdlet.ShouldProcess("", "Get-Credential"))
{
$Credential = Get-Credential -Message "Enter your client id as your username, and your client secret as your password. ***These values are being cached. Use Clear-StoreBrokerAuthentication or close this PowerShell window when you are done.***"
}
}
if ($null -eq $Credential)
{
if (-not $OnlyCacheTenantId)
{
Write-Log "No credential provided. Not changing current cached credential." -Level Error
}
}
else
{
if ($PSCmdlet.ShouldProcess($Credential, "Cache credential"))
{
$script:authCredential = $Credential
}
}
}
function Clear-StoreBrokerAuthentication
{
<#
.SYNOPSIS
Clears out any cached tenantId, client id, and client secret credential from this PowerShell session.
Also disables usage of the proxy server if that had been previously enabled.
All future remote commands from this module will once again prompt for credentials.
.DESCRIPTION
Clears out any cached tenantId, client id, and client secret credential from this PowerShell session.
Also disables usage of the proxy server if that had been previously enabled.
All future remote commands from this module will once again prompt for credentials.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.EXAMPLE
Clear-StoreBrokerAuthentication
Clears out any cached tenantId, client id, and client secret credential from this PowerShell session.
Also disables usage of the proxy server if that had been previously enabled.
All future remote commands from this module will once again prompt for credentials.
#>
[CmdletBinding(SupportsShouldProcess)]
param()
Set-TelemetryEvent -EventName Clear-StoreBrokerAuthentication
Write-Log "Executing: $($MyInvocation.Line)" -Level Verbose
if ($PSCmdlet.ShouldProcess("", "Clear tenantId"))
{
$script:authTenantId = $null
}
if ($PSCmdlet.ShouldProcess("", "Clear credential"))
{
$script:authCredential = $null
}
if ($PSCmdlet.ShouldProcess("", "Clear proxy"))
{
$script:proxyEndpoint = $null
}
if ($PSCmdlet.ShouldProcess("", "Clear tenantName"))
{
$script:tenantName = $null
}
}
function Get-AccessToken
{
<#
.SYNOPSIS
Gets an access token that can be used with the Windows Store Submission API REST requests.
.DESCRIPTION
Gets an access token that can be used with the Windows Store Submission API REST requests.
This token will only be valid for ONE HOUR.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER NoStatus
If this switch is specified, long-running commands will run on the main thread
with no commandline status update. When not specified, those commands run in
the background, enabling the command prompt to provide status information.
.EXAMPLE
$token = Get-AccessToken
Retrieves the access token that can be used in a future REST request header.
.OUTPUTS
System.String
.NOTES
The access token will only be valid for ONE HOUR.
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([String])]
param(
[switch] $NoStatus
)
# If we have a value for the proxy endpoint, that means we're using the proxy.
# In that scenario, we don't need to do any work here.
if (-not [String]::IsNullOrEmpty($script:proxyEndpoint))
{
# We can technically use any string in this scenario (even a null/empty string)
# since we don't require an accestoken to authenticate with the REST Proxy, but we'll
# use this string for debugging purposes.
return "PROXY"
}
if ([String]::IsNullOrEmpty($script:authTenantId))
{
$output = @()
$output += "You must call Set-StoreBrokerAuthentication to provide the tenantId"
$output += "before any of these cmdlets can be used. It will also cache your"
$output += "clientId and clientSecret as well. If you prefer to always be"
$output += "prompted for the client id and secret, use the -OnlyCacheTenantId switch"
$output += "when you call Set-StoreBrokerAuthentication."
$output += "To learn more on how to get these values, go to 'Installation and Setup' here:"
$output += " http://aka.ms/StoreBroker"
Write-Log $($output -join [Environment]::NewLine) -Level Error
throw "Halt Execution"
}
# Get our client id and secret, either from the cached credential or by prompting for them.
$credential = $script:authCredential
if ($null -eq $credential)
{
$output = @()
$output += "Prompting for credentials."
$output += "To avoid doing this every time, consider using Set-StoreBrokerAuthentication to cache the values for this session."
Write-Log $($output -join [Environment]::NewLine)
$credential = Get-Credential -Message "Enter your client id as your username, and your client secret as your password. ***To avoid getting this prompt every time, consider using Set-StoreBrokerAuthentication.***"
}
if ($null -eq $credential)
{
Write-Log "You must supply valid credentials (client id and secret) to use this module." -Level Error
throw "Halt Execution"
}
$clientId = $credential.UserName
$clientSecret = $credential.GetNetworkCredential().Password
# Constants
$tokenUrlFormat = "https://login.windows.net/{0}/oauth2/token"
$authBodyFormat = "grant_type=client_credentials&client_id={0}&client_secret={1}&resource={2}"
$serviceEndpoint = Get-ServiceEndpoint
# Need to make sure that the type is loaded before we attempt to access the HttpUtility methods.
# If we don't do this, we'll fail the first time we try to access the methods, but then it will
# work fine for consecutive attempts within the same console session.
Add-Type -AssemblyName System.Web
$url = $tokenUrlFormat -f $script:authTenantId
$body = $authBodyFormat -f
$([System.Web.HttpUtility]::UrlEncode($clientId)),
$([System.Web.HttpUtility]::UrlEncode($clientSecret)),
$serviceEndpoint
try
{
Write-Log -Message "Getting access token..." -Level Verbose
Write-Log "Accessing [POST] $url" -Level Verbose
if ($NoStatus)
{
if ($PSCmdlet.ShouldProcess($url, "Invoke-RestMethod"))
{
$response = Invoke-RestMethod $url -Method Post -Body $body
}
return $response.access_token
}
else
{
$jobName = "Get-AccessToken-" + (Get-Date).ToFileTime().ToString()
if ($PSCmdlet.ShouldProcess($jobName, "Start-Job"))
{
[scriptblock]$scriptBlock = {
param($url, $body)
Invoke-RestMethod $url -Method Post -Body $body
}
$null = Start-Job -Name $jobName -ScriptBlock $scriptBlock -Arg @($url, $body)
if ($PSCmdlet.ShouldProcess($jobName, "Wait-JobWithAnimation"))
{
Wait-JobWithAnimation -JobName $jobName -Description "Getting access token"
}
if ($PSCmdlet.ShouldProcess($jobName, "Receive-Job"))
{
$response = Receive-Job $jobName -AutoRemoveJob -Wait -ErrorAction SilentlyContinue -ErrorVariable remoteErrors
}
}
if ($remoteErrors.Count -gt 0)
{
throw $remoteErrors[0].Exception
}
# Keep track of how long this token will be valid for, to enable logic that re-uses
# the same token across multiple commands to known when a new one is necessary.
$script:accessTokenTimeoutSeconds = $response.expires_in - $script:accessTokenRefreshBufferSeconds
return $response.access_token
}
}
catch [System.InvalidOperationException]
{
# This type of exception occurs when using -NoStatus
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
$output = @()
$output += "Be sure to check that your client id/secret are valid."
$output += "StatusCode: $($_.Exception.Response.StatusCode.value__)"
$output += "StatusDescription: $($_.Exception.Response.StatusDescription)"
$output += "$($_.ErrorDetails | ConvertFrom-JSON | Out-String)"
Write-Log $($output -join [Environment]::NewLine) -Level Error
throw "Halt Execution"
}
catch [System.Management.Automation.RuntimeException]
{
# This type of exception occurs when NOT using -NoStatus
$output = @()
$output += "Be sure to check that your client id/secret are valid."
$output += "$($_.Exception.Message)"
if ($_.ErrorDetails.Message)
{
$message = ($_.ErrorDetails.Message | ConvertFrom-Json)
$output += "$($message.code) : $($message.message)"
if ($message.details)
{
$output += "$($message.details | Format-Table | Out-String)"
}
}
Write-Log $($output -join [Environment]::NewLine) -Level Error
throw "Halt Execution"
}
}
function Get-ServiceEndpoint
{
<#
.SYNOPSIS
Returns the appropriate service endpoint to use for API communication. By default, this
will always be PROD unless the user has specifically cofigured their environment to use
INT by setting $global:SBUseInt = $true.
.DESCRIPTION
Returns the appropriate service endpoint to use for API communication. By default, this
will always be PROD unless the user has specifically cofigured their environment to use
INT by setting $global:SBUseInt = $true.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.EXAMPLE
Get-ServiceEndpoint
Returns back the string representing the appropriate service endpoint, depending
on if the user has created and set a boolean value to $global:SBUseInt.
.OUTPUTS
String (the service endpoint URI)
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Justification="We use global variables sparingly and intentionally for module configuration, and employ a consistent naming convention.")]
param()
$serviceEndpointInt = "https://manage.devcenter.microsoft-int.com"
$serviceEndpointProd = "https://manage.devcenter.microsoft.com"
if (-not [String]::IsNullOrEmpty($script:proxyEndpoint))
{
if ($global:SBUseInt)
{
# Specifically logging this at the normal level because we want this to be SUPER clear
# to users so that they don't get confused by the results of their commands.
Write-Log "Using PROXY INT service endpoint. Return to PROD by setting `$global:SBUseInt = `$false"
}
else
{
Write-Log "Using PROXY PROD service endpoint" -Level Verbose
}
# The endpoint is the same for both in the Proxy case. But we'll add an additional
# header to the request when trying to use INT with the proxy. That's handled in
# Invoke-SBRestMethod.
return $script:proxyEndpoint
}
elseif ($global:SBUseInt)
{
# Specifically logging this at the normal level because we want this to be SUPER clear
# to users so that they don't get confused by the results of their commands.
Write-Log "Using INT service endpoint. Return to PROD by setting `$global:SBUseInt = `$false"
return $serviceEndpointInt
}
else
{
Write-Log "Using PROD service endpoint" -Level Verbose
return $serviceEndpointProd
}
}
function Get-AzureStorageDllPath
{
<#
.SYNOPSIS
Makes sure that the Microsoft.AzureStorage.dll assembly is available
on the machine, and returns the path to it.
.DESCRIPTION
Makes sure that the Microsoft.AzureStorage.dll assembly is available
on the machine, and returns the path to it.
This will first look for the assembly in the module's script directory.
Next it will look for the assembly in the location defined by
$SBAlternateAssemblyDir. This value would have to be defined by the user
prior to execution of this cmdlet.
If not found there, it will look in a temp folder established during this
PowerShell session.
If still not found, it will download the nuget package
for it to a temp folder accessible during this PowerShell session.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER NoStatus
If this switch is specified, long-running commands will run on the main thread
with no commandline status update. When not specified, those commands run in
the background, enabling the command prompt to provide status information.
.EXAMPLE
Get-AzureStorageDllPath
Returns back the path to the assembly as found. If the package has to
be downloaded via nuget, the command prompt will show a time duration
status counter while the package is being downloaded.
.EXAMPLE
Get-AzureStorageDllPath -NoStatus
Returns back the path to the assembly as found. If the package has to
be downloaded via nuget, the command prompt will appear to hang during
this time.
.OUTPUTS
System.String - The path to the Microsoft.WindowsStorage.dll assembly.
#>
[CmdletBinding(SupportsShouldProcess)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess", "", Justification="Methods called within here make use of PSShouldProcess, and the switch is passed on to them inherently.")]
param(
[switch] $NoStatus
)
$nugetPackageName = "WindowsAzure.Storage"
$nugetPackageVersion = "6.0.0"
$assemblyPackageTailDir = "WindowsAzure.Storage.6.0.0\lib\net40\"
$assemblyName = "Microsoft.WindowsAzure.Storage.dll"
return Get-NugetPackageDllPath -NugetPackageName $nugetPackageName -NugetPackageVersion $nugetPackageVersion -AssemblyPackageTailDirectory $assemblyPackageTailDir -AssemblyName $assemblyName -NoStatus:$NoStatus
}
function Set-SubmissionPackage
{
<#
.SYNOPSIS
Uploads the package to the URL provided after calling New-ApplicationSubmission.
.DESCRIPTION
Uploads the package to the URL provided after calling New-ApplicationSubmission.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER PackagePath
The package (zip) that contains all of the contents (appxupload/appxbundle/screenshots)
referenced by the submission.
.PARAMETER UploadUrl
The unique URL that was provided in response to a successful call to
New-ApplicationSubmission.
Supports Pipeline input.
.PARAMETER NoStatus
If this switch is specified, long-running commands will run on the main thread
with no commandline status update. When not specified, those commands run in
the background, enabling the command prompt to provide status information.
.EXAMPLE
Upload-SubmissionPackage "c:\foo.zip" "https://prodingestionbinaries1.blob.core.windows.net/ingestion/00000000-abcd-1234-0000-abcdefghijkl?sv=2014-02-14&sr=b&sig=WujGssA00/voXHaDgmaK1mpPn2JUkRPD/123gkAJdnI=&se=2015-12-17T12:58:14Z&sp=rwl"
Uploads the package content for the application submission,
with the console window showing progress while waiting for the upload to complete.
.EXAMPLE
Upload-SubmissionPackage "c:\foo.zip" "https://prodingestionbinaries1.blob.core.windows.net/ingestion/00000000-abcd-1234-0000-abcdefghijkl?sv=2014-02-14&sr=b&sig=WujGssA00/voXHaDgmaK1mpPn2JUkRPD/123gkAJdnI=&se=2015-12-17T12:58:14Z&sp=rwl" -NoStatus
Uploads the package content for the application submission,
but the request happens in the foreground and there is no additional status
shown to the user until the upload has completed.
.NOTES
This does not provide percentage completed status on the upload. It is only
able to provide the duration of the existing command (provided that you don't use
the -NoStatus switch).
This uses the "Set" verb to avoid Powershell import module warnings, but is then
aliased to Upload-ApplicationSubmissionPackage to better express what it is actually doing.
#>
[CmdletBinding(SupportsShouldProcess)]
[Alias('Set-ApplicationSubmissionPackage')]
[Alias('Upload-ApplicationSubmissionPackage')]
[Alias('Upload-SubmissionPackage')]
param(
[Parameter(Mandatory)]
[ValidateScript({if (Test-Path -Path $_ -PathType Leaf) { $true } else { throw "$_ cannot be found." }})]
[string] $PackagePath,
[Parameter(
Mandatory,
ValueFromPipeline=$True)]
[string] $UploadUrl,
[switch] $NoStatus
)
# Telemetry-related
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$telemetryProperties = @{ [StoreBrokerTelemetryProperty]::PackagePath = (Get-PiiSafeString -PlainText $PackagePath) }
Write-Log "Executing: $($MyInvocation.Line)" -Level Verbose
Write-Log "Attempting to upload the package ($PackagePath) for the submission to $UploadUrl..." -Level Verbose
$azureStorageDll = Get-AzureStorageDllPath -NoStatus:$NoStatus
try
{
if ($NoStatus)
{
$bytes = [System.IO.File]::ReadAllBytes($azureStorageDll)
[System.Reflection.Assembly]::Load($bytes) | Out-Null
$uri = New-Object -TypeName System.Uri -ArgumentList $UploadUrl
$cloudBlockBlob = New-Object -TypeName Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob -ArgumentList $uri
if ($PSCmdlet.ShouldProcess($PackagePath, "CloudBlockBlob.UploadFromFile"))
{
$result = $cloudBlockBlob.UploadFromFile($PackagePath, [System.IO.FileMode]::Open)
}
}
else
{
$jobName = "Set-SubmissionPackage-" + (Get-Date).ToFileTime().ToString()
if ($PSCmdlet.ShouldProcess($jobName, "Start-Job"))
{
[scriptblock]$scriptBlock = {
param($UploadUrl, $PackagePath, $AzureStorageDll)
$bytes = [System.IO.File]::ReadAllBytes($AzureStorageDll)
[System.Reflection.Assembly]::Load($bytes) | Out-Null
$uri = New-Object -TypeName System.Uri -ArgumentList $UploadUrl
$cloudBlockBlob = New-Object -TypeName Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob -ArgumentList $uri
$cloudBlockBlob.UploadFromFile($PackagePath, [System.IO.FileMode]::Open)
}
$null = Start-Job -Name $jobName -ScriptBlock $scriptBlock -Arg @($UploadUrl, $PackagePath, $azureStorageDll)
if ($PSCmdlet.ShouldProcess($jobName, "Wait-JobWithAnimation"))
{
Wait-JobWithAnimation -JobName $jobName -Description "Uploading $PackagePath"
}
if ($PSCmdlet.ShouldProcess($jobName, "Receive-Job"))
{
$result = Receive-Job $jobName -AutoRemoveJob -Wait -ErrorAction SilentlyContinue -ErrorVariable remoteErrors
}
}
if ($remoteErrors.Count -gt 0)
{
throw $remoteErrors[0].Exception
}
}
# Record the telemetry for this event.
$stopwatch.Stop()
$telemetryMetrics = @{ [StoreBrokerTelemetryMetric]::Duration = $stopwatch.Elapsed.TotalSeconds }
Set-TelemetryEvent -EventName Set-SubmissionPackage -Properties $telemetryProperties -Metrics $telemetryMetrics
}
catch [System.Management.Automation.RuntimeException]
{
# This type of exception occurs when NOT using -NoStatus
$output = @()
$output += "$($_.Exception.Message)"
if ($_.ErrorDetails.Message)
{
$message = ($_.ErrorDetails.Message | ConvertFrom-Json)
$output += "$($message.code) : $($message.message)"
if ($message.details)
{
$output += "$($message.details | Format-Table | Out-String)"
}
}
Set-TelemetryException -Exception $_.Exception -ErrorBucket Set-SubmissionPackage -Properties $telemetryProperties
Write-Log $($output -join [Environment]::NewLine) -Level Error
throw "Halt Execution"
}
catch
{
# This type of exception occurs when using -NoStatus
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
$output = @()
$output += "StatusCode: $($_.Exception.Response.StatusCode.value__)"
$output += "StatusDescription: $($_.Exception.Response.StatusDescription)"
$output += "$($_.ErrorDetails)"
Set-TelemetryException -Exception $_.Exception -ErrorBucket Set-SubmissionPackage -Properties $telemetryProperties
Write-Log $($output -join [Environment]::NewLine) -Level Error
throw "Halt Execution"
}
Write-Log "Successfully uploaded the application package." -Level Verbose
return $result
}
function Get-SubmissionPackage
{
<#
.SYNOPSIS
Downloads the existing package from the URL provided after calling New-ApplicationSubmission.
.DESCRIPTION
Downloads the existing package from the URL provided after calling New-ApplicationSubmission.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER UploadUrl
The unique URL that was provided in response to a successful call to
New-ApplicationSubmission.
Supports Pipeline input.
.PARAMETER PackagePath
The local path that you want to store the package (zip) that contains all of the contents
(appxupload/appxbundle/screenshots) referenced by the submission.
.PARAMETER NoStatus
If this switch is specified, long-running commands will run on the main thread
with no commandline status update. When not specified, those commands run in
the background, enabling the command prompt to provide status information.
.EXAMPLE
Get-SubmissionPackage "https://prodingestionbinaries1.blob.core.windows.net/ingestion/00000000-abcd-1234-0000-abcdefghijkl?sv=2014-02-14&sr=b&sig=WujGssA00/voXHaDgmaK1mpPn2JUkRPD/123gkAJdnI=&se=2015-12-17T12:58:14Z&sp=rwl" "c:\foo.zip"
Downloads the package content for the application submission to c:\foo.zip,
with the console window showing progress while awaiting for the download to complete.
.EXAMPLE
Get-SubmissionPackage "https://prodingestionbinaries1.blob.core.windows.net/ingestion/00000000-abcd-1234-0000-abcdefghijkl?sv=2014-02-14&sr=b&sig=WujGssA00/voXHaDgmaK1mpPn2JUkRPD/123gkAJdnI=&se=2015-12-17T12:58:14Z&sp=rwl" "c:\foo.zip" -NoStatus
Downloads the package content for the application submission to c:\foo.zip,
but the download happens in the foreground and there is no additional status
shown to the user until the download completes.
.NOTES
This does not provide percentage completed status on the download. It is only
able to provide the duration of the existing command (provided that you don't use
the -NoStatus switch).
#>
[CmdletBinding(SupportsShouldProcess)]
[Alias('Get-ApplicationSubmissionPackage')]
param(
[Parameter(
Mandatory,
ValueFromPipeline=$True)]
[string] $UploadUrl,
[Parameter(Mandatory)]
[ValidateScript({if (Test-Path -Path $_ -PathType Leaf) { throw "$_ already exists. Choose a different destination name." } else { $true }})]
[string] $PackagePath,
[switch] $NoStatus
)
# Telemetry-related
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$telemetryProperties = @{ [StoreBrokerTelemetryProperty]::PackagePath = (Get-PiiSafeString -PlainText $PackagePath) }
Write-Log "Executing: $($MyInvocation.Line)" -Level Verbose
Write-Log "Attempting to download the contents of $UploadUrl to $PackagePath..." -Level Verbose
$azureStorageDll = Get-AzureStorageDllPath -NoStatus:$NoStatus
try
{
if ($NoStatus)
{
$bytes = [System.IO.File]::ReadAllBytes($azureStorageDll)
[System.Reflection.Assembly]::Load($bytes) | Out-Null
$uri = New-Object -TypeName System.Uri -ArgumentList $UploadUrl
$cloudBlockBlob = New-Object -TypeName Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob -ArgumentList $uri
if ($PSCmdlet.ShouldProcess($PackagePath, "CloudBlockBlob.DownloadToFile"))
{
$result = $cloudBlockBlob.DownloadToFile($PackagePath, [System.IO.FileMode]::OpenOrCreate)
}
}
else
{
$jobName = "Get-ApplicationSubmissionPackage-" + (Get-Date).ToFileTime().ToString()
if ($PSCmdlet.ShouldProcess($jobName, "Start-Job"))
{
[scriptblock]$scriptBlock = {
param($UploadUrl, $PackagePath, $AzureStorageDll)
$bytes = [System.IO.File]::ReadAllBytes($AzureStorageDll)
[System.Reflection.Assembly]::Load($bytes) | Out-Null
$uri = New-Object -TypeName System.Uri -ArgumentList $UploadUrl
$cloudBlockBlob = New-Object -TypeName Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob -ArgumentList $uri
$cloudBlockBlob.DownloadToFile($PackagePath, [System.IO.FileMode]::OpenOrCreate)
}
$null = Start-Job -Name $jobName -ScriptBlock $scriptBlock -Arg @($UploadUrl, $PackagePath, $azureStorageDll)
if ($PSCmdlet.ShouldProcess($jobName, "Wait-JobWithAnimation"))
{
Wait-JobWithAnimation -JobName $jobName -Description "Downloading contents to $PackagePath"
}
if ($PSCmdlet.ShouldProcess($jobName, "Receive-Job"))
{
$result = Receive-Job $jobName -AutoRemoveJob -Wait -ErrorAction SilentlyContinue -ErrorVariable remoteErrors
}
}
if ($remoteErrors.Count -gt 0)
{
throw $remoteErrors[0].Exception
}
}
# Record the telemetry for this event.
$stopwatch.Stop()
$telemetryMetrics = @{ [StoreBrokerTelemetryMetric]::Duration = $stopwatch.Elapsed.TotalSeconds }
Set-TelemetryEvent -EventName Get-ApplicationSubmissionPackage -Properties $telemetryProperties -Metrics $telemetryMetrics
}
catch [System.Management.Automation.RuntimeException]
{
# This type of exception occurs when NOT using -NoStatus
$output = @()
$output += "$($_.Exception.Message)"
if ($_.ErrorDetails.Message)
{
$message = ($_.ErrorDetails.Message | ConvertFrom-Json)
$output += "$($message.code) : $($message.message)"
if ($message.details)
{
$output += "$($message.details | Format-Table | Out-String)"
}
}
Set-TelemetryException -Exception $_.Exception -ErrorBucket Get-ApplicationSubmissionPackage -Properties $telemetryProperties
Write-Log $($output -join [Environment]::NewLine) -Level Error
throw "Halt Execution"
}
catch
{
# This type of exception occurs when using -NoStatus
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
$output = @()
$output += "StatusCode: $($_.Exception.Response.StatusCode.value__)"
$output += "StatusDescription: $($_.Exception.Response.StatusDescription)"
$output += "$($_.ErrorDetails)"
Set-TelemetryException -Exception $_.Exception -ErrorBucket Get-ApplicationSubmissionPackage -Properties $telemetryProperties
Write-Log $($output -join [Environment]::NewLine) -Level Error
throw "Halt Execution"
}
Write-Log "Successfully downloaded the blob contents." -Level Verbose
return $result
}
function Start-SubmissionMonitor
{
<#
.SYNOPSIS
Auto-checks an application submission for status changes every 60 seconds with optional
email notification.
.DESCRIPTION
Auto-checks an application submission for status changes every 60 seconds with optional
email notification.
The monitoring will automatically end if the submission enters a failed state, or once
its state enters the final state that its targetPublishMode allows for.
The Git repo for this module can be found here: http://aka.ms/StoreBroker
.PARAMETER AppId
The Application ID for the application that has the committed submission.
.PARAMETER SubmissionId
The ID of the submission that should be monitored.
.PARAMETER EmailNotifyTo
A list of email addresses that should be emailed every time that status changes for
this submission.
.PARAMETER FlightId
This optional parameter, if provided, will treat the submission being monitored as a
flight submission as opposed to an application submission.
.PARAMETER IapId
If provided, this will treat the submission being monitored as an In-App Product
submission as opposed to an application submission.
.PARAMETER NoStatus
If this switch is specified, long-running commands will run on the main thread
with no commandline status update. When not specified, those commands run in