-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathAutomationISEControl.xaml.cs
3514 lines (3245 loc) · 176 KB
/
AutomationISEControl.xaml.cs
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 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.PowerShell.Host.ISE;
using Microsoft.Azure.Management.Automation.Models;
using AutomationISE.Model;
using System.IO;
using System.Threading;
using System.Windows.Threading;
using System.Linq;
using System.Diagnostics;
using System.Timers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Security.Cryptography.X509Certificates;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Media.Animation;
using System.Text;
using System.Drawing;
using System.Net;
using System.Management.Automation;
using Microsoft.Azure.Management.Storage.Models;
using System.Management.Automation.Runspaces;
namespace AutomationISE
{
/// <summary>
/// Interaction logic for AutomationISEControl.xaml
/// </summary>
public partial class AutomationISEControl : UserControl, IAddOnToolHostObject
{
private System.Timers.Timer refreshAccountDataTimer;
private System.Timers.Timer refreshAuthTokenTimer;
private AutomationISEClient iseClient;
private ObservableCollection<AutomationRunbook> runbookListViewModel;
private ObservableCollection<AutomationDSC> DSCListViewModel;
private ObservableCollection<AutomationAsset> assetListViewModel;
private ObservableCollection<AutomationModule> moduleListViewModel;
private ISet<ConnectionType> connectionTypes;
private ISet<AutomationAsset> assets;
private ListSortDirection runbookCurrSortDir;
private string runbookCurrSortProperty;
private ListSortDirection configurationCurrSortDir;
private string configurationCurrSortProperty;
private ListSortDirection moduleCurrSortDir;
private string moduleCurrSortProperty;
private ListSortDirection assetCurrSortDir;
private string assetCurrSortProperty;
private int numBackgroundTasks = 0;
private Object backgroundWorkLock;
private Object refreshScriptsLock;
private Object refreshModulesLock;
private Storyboard progressSpinnerStoryboard;
private Storyboard progressSpinnerStoryboardReverse;
private Storyboard miniProgressSpinnerStoryboard;
private Storyboard miniProgressSpinnerStoryboardReverse;
private bool promptShortened;
private string certificateThumbprint;
private FileSystemWatcher fileWatcher;
private string VSStudio;
private string VSCode;
public ObjectModelRoot HostObject { get; set; }
string lastUpdated = "";
private string addOnVersion = null;
Dictionary<string, string> localScriptsParsed = new Dictionary<string, string>();
Dictionary<string, PSObject> localModulesParsed = new Dictionary<string, PSObject>();
private bool collectUsage = true;
public AutomationISEControl()
{
try
{
InitializeComponent();
iseClient = new AutomationISEClient();
/* Spinner animation stuff */
backgroundWorkLock = new Object();
refreshScriptsLock = new Object();
refreshModulesLock = new Object();
progressSpinnerStoryboard = (Storyboard)FindResource("bigGearRotationStoryboard");
progressSpinnerStoryboardReverse = (Storyboard)FindResource("bigGearRotationStoryboardReverse");
miniProgressSpinnerStoryboard = (Storyboard)FindResource("smallGearRotationStoryboard");
miniProgressSpinnerStoryboardReverse = (Storyboard)FindResource("smallGearRotationStoryboardReverse");
/* Determine working directory */
String localWorkspace = Properties.Settings.Default["localWorkspace"].ToString();
if (localWorkspace == "")
{
String userProfile = Environment.GetEnvironmentVariable("USERPROFILE") + "\\";
localWorkspace = System.IO.Path.Combine(userProfile, "AutomationWorkspace");
Properties.Settings.Default["localWorkspace"] = localWorkspace;
Properties.Settings.Default.Save();
}
iseClient.baseWorkspace = localWorkspace;
promptShortened = false;
/* Initialize Timers */
refreshAccountDataTimer = new System.Timers.Timer();
refreshAccountDataTimer.Interval = 30000; //30 seconds
refreshAccountDataTimer.Elapsed += new ElapsedEventHandler(refreshAccountData);
refreshAuthTokenTimer = new System.Timers.Timer();
refreshAuthTokenTimer.Interval = Constants.tokenRefreshInterval * 60000;
refreshAuthTokenTimer.Elapsed += new ElapsedEventHandler(refreshAuthToken);
/* Set up file system watcher */
fileWatcher = new System.IO.FileSystemWatcher();
/* Update UI */
workspaceTextBox.Text = iseClient.baseWorkspace;
userNameTextBox.Text = Properties.Settings.Default["ADUserName"].ToString();
subscriptionComboBox.IsEnabled = false;
accountsComboBox.IsEnabled = false;
assetsComboBox.Items.Add(AutomationISE.Model.Constants.assetConnection);
assetsComboBox.Items.Add(AutomationISE.Model.Constants.assetCredential);
assetsComboBox.Items.Add(AutomationISE.Model.Constants.assetVariable);
assetsComboBox.Items.Add(AutomationISE.Model.Constants.assetCertificate);
setCreationButtonStatesTo(false);
setAllAssetButtonStatesTo(false);
assetsComboBox.IsEnabled = false;
setAllRunbookButtonStatesTo(false);
setAllConfigurationButtonStatesTo(false);
ButtonRefreshModule.IsEnabled = false;
// Generate self-signed certificate for encrypting local assets in the current user store Cert:\CurrentUser\My\
var certObj = new AutomationSelfSignedCertificate();
certificateThumbprint = certObj.CreateSelfSignedCertificate(iseClient.baseWorkspace);
certificateTextBox.Text = certificateThumbprint;
UpdateStatusBox(configurationStatusTextBox, "Thumbprint of certificate used to encrypt local assets: " + certificateThumbprint);
// Load feedback and help page preemptively
addOnVersion = PowerShellGallery.GetLocalVersion();
surveyBrowserControl.Navigate(new Uri(Constants.feedbackURI));
helpBrowserControl.Navigate(new Uri(Constants.helpURI + "?version=" + addOnVersion));
// Check if this is the latest version from PowerShell Gallery
if (PowerShellGallery.CheckGalleryVersion())
{
versionLabel.Foreground = System.Windows.Media.Brushes.Red;
versionLabel.Content = "New AzureAutomationAuthoringToolkit available";
}
else
{
versionLabel.Visibility = Visibility.Collapsed;
versionButton.Visibility = Visibility.Collapsed;
}
runAscheckBox.IsChecked = Properties.Settings.Default.RunAs;
IDEComboBox.Visibility = Visibility.Collapsed;
IDEEditorLabel.Visibility = Visibility.Collapsed;
AzureEnvironmentComboBox.Items.Add("Public Azure");
AzureEnvironmentComboBox.Items.Add("US Government Azure");
String AzureEnvironment = Properties.Settings.Default.loginAuthority;
if (AzureEnvironment == Constants.publicLoginAuthority)
{
AzureEnvironmentComboBox.SelectedItem = "Public Azure";
}
if (AzureEnvironment == Constants.USGovernmentLoginAuthority)
{
AzureEnvironmentComboBox.SelectedItem = "US Government Azure";
}
}
catch (Exception exception)
{
var detailsDialog = System.Windows.Forms.MessageBox.Show(exception.Message);
}
}
/// <summary>
/// Checks when a property changes on selected tab
/// If the property change is getting focus, then update the runbook list to match this
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CurrentPowerShellTab_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (HostObject != null)
{
if (e.PropertyName == "LastEditorWithFocus")
{
if (runbookListViewModel != null && DSCListViewModel != null && HostObject.CurrentPowerShellTab.Files.Count > 0)
{
foreach (AutomationRunbook runbook in runbookListViewModel)
{
if (runbook.Name.Equals(Path.GetFileNameWithoutExtension(HostObject.CurrentPowerShellTab.Files.SelectedFile.DisplayName)))
{
RunbooksListView.SelectedItem = runbook;
RunbooksListView.ScrollIntoView(RunbooksListView.SelectedItem);
break;
}
}
foreach (AutomationDSC configuration in DSCListViewModel)
{
if (configuration.localFileInfo != null)
{
if (Path.GetFileNameWithoutExtension(configuration.localFileInfo.ToString()).Equals(Path.GetFileNameWithoutExtension(HostObject.CurrentPowerShellTab.Files.SelectedFile.DisplayName)))
{
DSCListView.SelectedItem = configuration;
DSCListView.ScrollIntoView(DSCListView.SelectedItem);
break;
}
}
}
}
}
}
}
public String getEncryptionCertificateThumbprint()
{
return certificateThumbprint;
}
public void setCreationButtonStatesTo(bool enabled)
{
ButtonNewAsset.IsEnabled = enabled;
ButtonCreateRunbook.IsEnabled = enabled;
ButtonCreateConfiguration.IsEnabled = enabled;
}
public void setAllRunbookButtonStatesTo(bool enabled)
{
ButtonDeleteRunbook.IsEnabled = enabled;
ButtonDownloadRunbook.IsEnabled = enabled;
ButtonOpenRunbook.IsEnabled = enabled;
ButtonUploadRunbook.IsEnabled = enabled;
ButtonTestRunbook.IsEnabled = enabled;
ButtonPublishRunbook.IsEnabled = enabled;
}
public void setAllConfigurationButtonStatesTo(bool enabled)
{
ButtonDeleteConfiguration.IsEnabled = enabled;
ButtonDownloadConfiguration.IsEnabled = enabled;
ButtonOpenConfiguration.IsEnabled = enabled;
ButtonUploadConfiguration.IsEnabled = enabled;
ButtonCompileConfiguration.IsEnabled = enabled;
}
public void setAllModuleButtonStatesTo(bool enabled)
{
ButtonDeleteModule.IsEnabled = enabled;
ButtonUploadModule.IsEnabled = enabled;
}
public void setAllAssetButtonStatesTo(bool enabled)
{
ButtonDownloadAsset.IsEnabled = enabled;
ButtonEditAsset.IsEnabled = enabled;
ButtonDeleteAssets.IsEnabled = enabled;
ButtonUploadAsset.IsEnabled = enabled;
ButtonInsertAssets.IsEnabled = enabled;
}
public IList<AutomationAsset> getSelectedAssets()
{
IList items = (System.Collections.IList)assetsListView.SelectedItems;
return items.Cast<AutomationAsset>().ToList<AutomationAsset>();
}
public void setSelectedAssets(IList<AutomationAsset> assetsToSelect)
{
var assetsToSelectSet = new HashSet<string>();
foreach (AutomationAsset asset in assetsToSelect) {
assetsToSelectSet.Add(asset.Name);
}
foreach (AutomationAsset asset in assetListViewModel)
{
if(assetsToSelectSet.Contains(asset.Name)) {
assetsListView.SelectedItems.Add(asset);
}
}
}
public async Task<ISet<ConnectionType>> getConnectionTypes()
{
return await AutomationAssetManager.GetConnectionTypes(iseClient.automationManagementClient, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name);
}
public SortedSet<AutomationAsset> getAssetsOfType(String type)
{
var assetsOfType = new SortedSet<AutomationAsset>();
foreach (var asset in assets)
{
if (asset.GetType().Name == type)
{
assetsOfType.Add(asset);
}
}
return assetsOfType;
}
public async Task downloadAllAssets()
{
try
{
if (connectionTypes != null) connectionTypes.Clear();
await AutomationAssetManager.DownloadAllFromCloud(iseClient.currWorkspace, iseClient.automationManagementClient, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name, getEncryptionCertificateThumbprint(), connectionTypes);
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
}
public void downloadAssets(ICollection<AutomationAsset> assetsToDownload)
{
try
{
AutomationAssetManager.DownloadFromCloud(assetsToDownload, iseClient.currWorkspace, iseClient.automationManagementClient, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name, getEncryptionCertificateThumbprint(), connectionTypes);
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
}
public async Task uploadAssets(ICollection<AutomationAsset> assetsToUpload)
{
try
{
await AutomationAssetManager.UploadToCloud(assetsToUpload, iseClient.automationManagementClient, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name);
// Since the cloud assets uploaded will have a last modified time of now, causing them to look newer than their local counterparts,
// download the assets after upload to force last modified time between local and cloud to be the same, showing them as in sync (which they are)
downloadAssets(assetsToUpload);
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
}
public void deleteAssets(ICollection<AutomationAsset> assetsToDelete)
{
try
{
bool deleteLocally = true;
bool deleteFromCloud = true;
// when asset is only local or only in cloud, we know where they want to delete it from. But when asset is both local and cloud,
// they may not have meant to delete it from cloud, so ask them
foreach (var assetToDelete in assetsToDelete)
{
if (assetToDelete.LastModifiedCloud != null && assetToDelete.LastModifiedLocal != null)
{
var messageBoxResult = System.Windows.Forms.MessageBox.Show(
"At least some of the selected assets have both local and cloud versions. Do you want to also delete the cloud versions of these assets?",
"Delete Confirmation",
System.Windows.Forms.MessageBoxButtons.YesNoCancel, System.Windows.Forms.MessageBoxIcon.Warning
);
if (messageBoxResult == System.Windows.Forms.DialogResult.No)
{
deleteFromCloud = false;
}
else if (messageBoxResult == System.Windows.Forms.DialogResult.Cancel)
{
deleteFromCloud = false;
deleteLocally = false;
}
break;
}
}
AutomationAssetManager.Delete(assetsToDelete, iseClient.currWorkspace, iseClient.automationManagementClient, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name, deleteLocally, deleteFromCloud, getEncryptionCertificateThumbprint(), connectionTypes);
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
}
}
public void refreshAuthToken(object source, ElapsedEventArgs e)
{
try
{
refreshAuthTokenTimer.Stop();
iseClient.RefreshAutomationClientwithNewToken();
refreshAuthTokenTimer.Start();
if (refreshAccountDataTimer.Enabled == false) refreshAccountDataTimer.Start();
}
catch (Exception exception)
{
refreshAuthTokenTimer.Stop();
loginButton.Content = "Sign In";
System.Windows.Forms.MessageBox.Show("Your session expired and could not be refreshed. Please sign in again./r/nDetails: " + exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
public void refreshAccountData(object source, ElapsedEventArgs e)
{
this.Dispatcher.Invoke(() =>
{
try
{
Task t = refreshRunbooks();
t = refreshAssets();
t = refreshConfigurations();
}
catch (Exception exception)
{
refreshAccountDataTimer.Stop();
int tokenExpiredResult = -2146233088;
if (exception.HResult == tokenExpiredResult)
{
iseClient.RefreshAutomationClientwithNewToken();
}
else
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
});
}
private async Task<Boolean> CheckRunAs()
{
// Indicates whether the RunAs can be used successfully.
var runAsSuccess = false;
try
{
// Check if local runas certificate is available in the automation account
AutomationConnection runAsConnection = (AutomationConnection)assets.FirstOrDefault(x => x.Name == "AzureRunAsConnection" && x.GetType().Name == "AutomationConnection");
if (runAsConnection == null)
{
System.Windows.Forms.MessageBox.Show("RunAs account is not configured. Please create from the portal", "Warning", System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Warning);
return false;
}
// Check if a certificate for RunAs is already present. It will be in the form (RunAs + account name + hostname)
AutomationCertificate certificateAsset = (AutomationCertificate)assets.FirstOrDefault(x => x.Name == ("RunAs" + ((AutomationAccount)accountsComboBox.SelectedValue).Name + Dns.GetHostName()) && x.GetType().Name == "AutomationCertificate");
// If certificate is present in cloud, update RunAsConnection connection thumbprint if needed
if (certificateAsset != null && certificateAsset.SyncStatus != "Local Only")
{
var assetsToSave = new List<AutomationAsset>();
var thumbprint = certificateAsset.getThumbprint();
var connectionFields = runAsConnection.getFields();
// If local RunAs connection does not contain the local certificate thumprint, then update it
if (connectionFields["CertificateThumbprint"].ToString() != thumbprint)
{
connectionFields["CertificateThumbprint"] = thumbprint;
assetsToSave.Add(runAsConnection);
}
// Update RunAsCertificate to point to this local certificate
AutomationCertificate runAsCertificate = (AutomationCertificate)assets.FirstOrDefault(x => x.Name == "AzureRunAsCertificate" && x.GetType().Name == "AutomationCertificate");
runAsCertificate.setThumbprint(thumbprint);
assetsToSave.Add(runAsCertificate);
AutomationAssetManager.SaveLocally(iseClient.currWorkspace, assetsToSave, getEncryptionCertificateThumbprint(), connectionTypes);
refreshAssets();
certificateAsset.UpdateSyncStatus();
runAsCertificate.UpdateSyncStatus();
runAsSuccess = true;
}
else
{
// Create local cert and upload to the cloud
// Refresh token to work against graph API
var token = AuthenticateHelper.RefreshTokenByAuthority(iseClient.currSubscription.Authority, Constants.graphURI);
// Create new instance of the runAsClient so we can update the AD application with the new certificate
var runAsClient = new RunAs(token);
// Create certificate and update AD application with new certificate
var connectionFields = runAsConnection.getFields();
var newCertificate = await runAsClient.CreateLocalRunAs(connectionFields["ApplicationId"].ToString(), "RunAs" + ((AutomationAccount)accountsComboBox.SelectedValue).Name + Dns.GetHostName());
if (newCertificate != null)
{
// Upload local certificate to automation account so it could work in the service also
// if the local RunAs connection is uploaded.
var properties = new CertificateCreateOrUpdateProperties()
{
Base64Value = Convert.ToBase64String(newCertificate.Export(X509ContentType.Pkcs12)),
Thumbprint = newCertificate.Thumbprint,
IsExportable = true
};
var cts = new CancellationTokenSource();
cts.CancelAfter(30000);
await iseClient.automationManagementClient.Certificates.CreateOrUpdateAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name, new CertificateCreateOrUpdateParameters(newCertificate.FriendlyName, properties), cts.Token);
// Update RunAs connection with the new certificate
connectionFields["CertificateThumbprint"] = newCertificate.Thumbprint;
var assetsToSave = new List<AutomationAsset>();
assetsToSave.Add(runAsConnection);
// Update RunAsCertificate to point to this local certificate
AutomationCertificate runAsCertificate = (AutomationCertificate)assets.FirstOrDefault(x => x.Name == "AzureRunAsCertificate" && x.GetType().Name == "AutomationCertificate");
runAsCertificate.setThumbprint(newCertificate.Thumbprint);
assetsToSave.Add(runAsCertificate);
// Save new certificate to local assets store.
var newCert = new AutomationCertificate(newCertificate.FriendlyName, newCertificate.Thumbprint, null, null, true, true);
assetsToSave.Add(newCert);
AutomationAssetManager.SaveLocally(iseClient.currWorkspace, assetsToSave, getEncryptionCertificateThumbprint(), connectionTypes);
// Refresh assets and set sync status
refreshAssets();
newCert.UpdateSyncStatus();
runAsSuccess = true;
}
}
}
catch (Exception Ex)
{
System.Windows.Forms.MessageBox.Show("Error configuring RunAs: " + Ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
runAsSuccess = false;
}
return runAsSuccess;
}
public async Task refreshAssets(bool useExistingAssetValues = false)
{
try
{
if (!useExistingAssetValues)
{
assets = await AutomationAssetManager.GetAll(iseClient.currWorkspace, iseClient.automationManagementClient, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name, getEncryptionCertificateThumbprint(), connectionTypes);
}
var selectedAssets = getSelectedAssets();
string selectedAssetType = (string)assetsComboBox.SelectedValue;
if (selectedAssetType == null) return;
if (selectedAssetType == AutomationISE.Model.Constants.assetVariable)
{
mergeAssetListWith(getAssetsOfType("AutomationVariable"));
}
else if (selectedAssetType == AutomationISE.Model.Constants.assetCredential)
{
mergeAssetListWith(getAssetsOfType("AutomationCredential"));
}
else if (selectedAssetType == AutomationISE.Model.Constants.assetConnection)
{
mergeAssetListWith(getAssetsOfType("AutomationConnection"));
}
else if (selectedAssetType == AutomationISE.Model.Constants.assetCertificate)
{
mergeAssetListWith(getAssetsOfType("AutomationCertificate"));
}
setSelectedAssets(selectedAssets);
connectionTypes = await getConnectionTypes();
}
catch (Exception exception)
{
int tokenExpiredResult = -2146233088;
if (exception.HResult == tokenExpiredResult)
{
refreshAccountDataTimer.Stop();
loginButton.Content = "Sign In";
}
if (exception.HResult == -2146233029)
{
// Waiting for data error from query. Ignore this as it is transient.
}
else
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
}
private void mergeAssetListWith(ICollection<AutomationAsset> newAssetCollection)
{
assetListViewModel.Clear();
foreach (AutomationAsset asset in newAssetCollection) {
assetListViewModel.Add(asset);
}
}
private async void loginButton_Click(object sender, RoutedEventArgs e)
{
try
{
ScriptAnalyzerTextBlock_ISEAddon.Visibility = Visibility.Collapsed;
UpdateStatusBox(configurationStatusTextBox, "Launching login window...");
if (loginButton.Content.ToString() == "Sign In")
iseClient.azureADAuthResult = AutomationISE.Model.AuthenticateHelper.GetInteractiveLogin(userNameTextBox.Text);
else
iseClient.azureADAuthResult = AutomationISE.Model.AuthenticateHelper.GetInteractiveLogin(userNameTextBox.Text,"common",true);
loginButton.Content = "Switch User";
refreshAccountDataTimer.Stop();
if (HostObject == null)
{
IDEComboBox.Items.Clear();
IDEEditorLabel.Visibility = Visibility.Visible;
IDEComboBox.Visibility = Visibility.Visible;
String editor = Properties.Settings.Default["Editor"].ToString();
VSStudio = GetVisualStudioPath();
if (VSStudio != null)
{
IDEComboBox.Items.Add("Visual Studio");
}
VSCode = GetVSCodePath();
if (VSCode != null)
{
IDEComboBox.Items.Add("VS Code");
}
if (!String.IsNullOrEmpty(editor))
IDEComboBox.SelectedValue = editor;
else
{
if (IDEComboBox.HasItems)
IDEComboBox.SelectedItem = IDEComboBox.Items[0];
}
togglePromptButton.Visibility = Visibility.Collapsed;
ButtonInsertAssets.Content = "Copy to clipboard";
}
beginBackgroundWork(Properties.Resources.RetrieveSubscriptions);
userNameTextBox.Text = iseClient.azureADAuthResult.UserInfo.DisplayableId;
UpdateStatusBox(configurationStatusTextBox, "Logged in user: " + userNameTextBox.Text);
Properties.Settings.Default["ADUserName"] = userNameTextBox.Text;
Properties.Settings.Default.Save();
subscriptionComboBox.ItemsSource = null;
IList<AutomationISEClient.SubscriptionObject> subscriptions = await iseClient.GetSubscriptions();
if (subscriptions.Count > 0)
{
endBackgroundWork(Properties.Resources.FoundSubscriptions);
var subscriptionList = subscriptions.OrderBy(x => x.Name);
subscriptionComboBox.ItemsSource = subscriptionList;
subscriptionComboBox.DisplayMemberPath = "Name";
foreach (AutomationISEClient.SubscriptionObject selectedSubscription in subscriptionComboBox.Items)
{
if (selectedSubscription.SubscriptionId == Properties.Settings.Default.lastSubscription.ToString())
{
subscriptionComboBox.SelectedItem = selectedSubscription;
}
}
if (subscriptionComboBox.SelectedItem == null)
{
subscriptionComboBox.SelectedItem = subscriptionComboBox.Items[0];
}
subscriptionComboBox.IsEnabled = false;
refreshAuthTokenTimer.Start();
}
else
{
endBackgroundWork(Properties.Resources.NoSubscriptions);
}
if (HostObject != null) { HostObject.CurrentPowerShellTab.PropertyChanged += new PropertyChangedEventHandler(CurrentPowerShellTab_PropertyChanged); }
}
catch (Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException Ex)
{
int userCancelResult = -2146233088;
if (Ex.HResult == userCancelResult)
UpdateStatusBox(configurationStatusTextBox, Properties.Resources.CancelSignIn);
else
UpdateStatusBox(configurationStatusTextBox, "Sign-in error: " + Ex.ErrorCode.ToString() + " Error Message: " + Ex.Message);
}
catch (Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException Ex)
{
int userCancelResult = -2146233088;
if (Ex.HResult == userCancelResult)
UpdateStatusBox(configurationStatusTextBox, Properties.Resources.CancelSignIn);
else
UpdateStatusBox(configurationStatusTextBox, "Sign-in error: " + Ex.ErrorCode.ToString() + " Error Message: " + Ex.Message);
}
catch (Exception Ex)
{
endBackgroundWork("Couldn't retrieve subscriptions.");
var detailsDialog = System.Windows.Forms.MessageBox.Show(Ex.InnerException.Message);
}
}
private async void SubscriptionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
subscriptionComboBox.IsEnabled = false;
accountsComboBox.IsEnabled = false;
assetsComboBox.IsEnabled = false;
refreshAccountDataTimer.Stop();
// Save the last selected subscription so we default to this one next time the ISE is openend
if (subscriptionComboBox.SelectedItem != null)
{
var selectedSubscription = (AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedValue;
if (selectedSubscription.Name != null)
{
Properties.Settings.Default.lastSubscription = selectedSubscription.SubscriptionId;
Properties.Settings.Default.Save();
}
iseClient.currSubscription = (AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedValue;
if (iseClient.currSubscription.Name != null)
{
beginBackgroundWork(Properties.Resources.RetrieveAutomationAccounts);
IList<AutomationAccount> automationAccounts = await iseClient.GetAutomationAccounts();
var accountList = automationAccounts.OrderBy(x => x.Name);
accountsComboBox.ItemsSource = accountList;
accountsComboBox.DisplayMemberPath = "Name";
if (accountsComboBox.HasItems)
{
endBackgroundWork(Properties.Resources.FoundAutomationAccounts);
var lastAccountName = Properties.Settings.Default.lastAutomationAccount;
if (lastAccountName != "")
{
// find if automation account is present in list
foreach (AutomationAccount selectedAccount in accountsComboBox.Items)
{
if (selectedAccount.Name.ToString() == Properties.Settings.Default.lastAutomationAccount.ToString())
{
accountsComboBox.SelectedItem = selectedAccount;
}
}
if (accountsComboBox.SelectedItem == null) accountsComboBox.SelectedItem = accountsComboBox.Items[0];
}
else
{
accountsComboBox.SelectedItem = accountsComboBox.Items[0];
}
accountsComboBox.IsEnabled = true;
}
else
{
endBackgroundWork(Properties.Resources.NoAutomationAccounts);
}
}
}
subscriptionComboBox.IsEnabled = true;
}
catch (Exception exception)
{
endBackgroundWork("Couldn't retrieve Automation Accounts.");
subscriptionComboBox.IsEnabled = true;
assetsComboBox.IsEnabled = false;
var detailsDialog = System.Windows.Forms.MessageBox.Show(exception.Message);
}
}
private async void accountsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
AutomationAccount account = (AutomationAccount)accountsComboBox.SelectedValue;
accountsComboBox.IsEnabled = false;
ButtonRefreshModule.IsEnabled = false;
iseClient.currAccount = account;
refreshAccountDataTimer.Stop();
if (account != null)
{
/* Update Status */
UpdateStatusBox(configurationStatusTextBox, "Selected automation account: " + account.Name);
Properties.Settings.Default.lastAutomationAccount = account.Name;
Properties.Settings.Default.Save();
if (iseClient.AccountWorkspaceExists())
accountPathTextBox.Text = iseClient.currWorkspace;
// Refresh local modules
//Set up module view and start looking for modules
if (runbookListViewModel != null) runbookListViewModel.Clear();
ModuleListView.ItemsSource = null;
if (moduleListViewModel != null) moduleListViewModel.Clear();
RefreshModulesTask();
moduleListViewModel = new ObservableCollection<AutomationModule>();
/* Update Runbooks */
beginBackgroundWork("Getting account data");
beginBackgroundWork("Getting runbook data for " + account.Name);
if (runbookListViewModel != null) runbookListViewModel.Clear();
if (assetListViewModel != null) assetListViewModel.Clear();
localScriptsParsed = null;
await refreshLocalScripts();
var localScripts = await getLocalScripts();
runbookListViewModel = new ObservableCollection<AutomationRunbook>(await AutomationRunbookManager.GetAllRunbookMetadata(iseClient.automationManagementClient,
iseClient.currWorkspace, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name,localScripts));
endBackgroundWork("Done getting runbook data");
/* Update Configurations */
beginBackgroundWork("Getting configuration data for " + account.Name);
if (DSCListViewModel != null) DSCListViewModel.Clear();
if (assetListViewModel != null) assetListViewModel.Clear();
DSCListViewModel = new ObservableCollection<AutomationDSC>(await AutomationDSCManager.GetAllConfigurationMetadata(iseClient.automationManagementClient,
iseClient.currWorkspace, iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name, localScripts));
endBackgroundWork("Done getting configuration data");
/* Update Assets */
beginBackgroundWork("Downloading assets for " + account.Name);
//TODO: this is not quite checking what we need it to check
if (!iseClient.AccountWorkspaceExists())
{
await downloadAllAssets();
}
assetListViewModel = new ObservableCollection<AutomationAsset>();
await refreshAssets(); //populates the viewmodel
endBackgroundWork("Assets downloaded.");
/* Update PowerShell Module */
try
{
PSModuleConfiguration.UpdateModuleConfiguration(iseClient.currWorkspace);
}
catch
{
string message = "Could not configure the " + PSModuleConfiguration.ModuleData.ModuleName + " module.\r\n";
message += "This module is required for your runbooks to run locally.\r\n";
message += "Make sure it exists in your module path (env:PSModulePath).";
System.Windows.Forms.MessageBox.Show(message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
/* Update UI */
RunbooksListView.ItemsSource = runbookListViewModel;
CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(RunbooksListView.ItemsSource);
view.Filter = FilterRunbook;
RunbooksListView.Items.SortDescriptions.Clear();
RunbooksListView.Items.SortDescriptions.Add(new SortDescription("LastModifiedLocal", ListSortDirection.Descending));
DSCListView.ItemsSource = DSCListViewModel;
CollectionView DSCview = (CollectionView)CollectionViewSource.GetDefaultView(DSCListView.ItemsSource);
DSCview.Filter = FilterConfiguration;
DSCListView.Items.SortDescriptions.Clear();
DSCListView.Items.SortDescriptions.Add(new SortDescription("LastModifiedLocal", ListSortDirection.Descending));
ModuleListView.ItemsSource = moduleListViewModel;
RefreshModulesTask();
CollectionView Moduleview = (CollectionView)CollectionViewSource.GetDefaultView(ModuleListView.ItemsSource);
Moduleview.Filter = FilterModule;
ModuleListView.Items.SortDescriptions.Clear();
ModuleListView.Items.SortDescriptions.Add(new SortDescription("LastModifiedCloud", ListSortDirection.Descending));
assetsListView.ItemsSource = assetListViewModel;
// Set credentials assets to be selected
assetsComboBox.SelectedItem = assetsComboBox.Items[1];
setAllRunbookButtonStatesTo(false);
setAllConfigurationButtonStatesTo(false);
setCreationButtonStatesTo(true);
assetsComboBox.IsEnabled = true;
subscriptionComboBox.IsEnabled = true;
/* Enable source control sync in Azure Automation if it is set up for this automation account */
bool isSourceControlEnabled = await AutomationSourceControl.isSourceControlEnabled(iseClient.automationManagementClient,
iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name);
if (isSourceControlEnabled)
{
ButtonSourceControlRunbook.Visibility = Visibility.Visible;
ButtonSourceControlRunbook.IsEnabled = true;
}
else ButtonSourceControlRunbook.Visibility = Visibility.Collapsed;
/* Change current directory to new workspace location */
accountPathTextBox.Text = iseClient.currWorkspace;
string pathHint = Path.GetPathRoot(iseClient.currWorkspace) + "..." + Path.DirectorySeparatorChar + Path.GetFileName(iseClient.currWorkspace);
if (HostObject != null)
{
HostObject.CurrentPowerShellTab.InvokeSynchronous("cd \"" + iseClient.currWorkspace + "\"" + ";function prompt {'PS " + pathHint + "> '}", false, 5000);
}
promptShortened = true;
endBackgroundWork("Finished getting data for " + account.Name);
refreshAccountDataTimer.Start();
if (Properties.Settings.Default.RunAs)
{
if (await CheckRunAs())
{
// Use RunAs connection in account to authenticate with Azure.
if (HostObject != null)
{
HostObject.CurrentPowerShellTab.Invoke("$RunAsConnection = Get-AutomationConnection -Name AzureRunAsConnection;try {$Login=Add-AzureRmAccount -ServicePrincipal -TenantId $RunAsConnection.TenantId -ApplicationId $RunAsConnection.ApplicationId -CertificateThumbprint $RunAsConnection.CertificateThumbprint -ErrorAction Stop}catch{Sleep 10;$Login=Add-AzureRmAccount -ServicePrincipal -TenantId $RunAsConnection.TenantId -ApplicationId $RunAsConnection.ApplicationId -CertificateThumbprint $RunAsConnection.CertificateThumbprint};Set-AzureRmContext -SubscriptionId $RunAsConnection.SubscriptionID");
}
}
}
/* Set up file watch on the current workspace */
fileWatcher.Path = iseClient.currWorkspace + "\\";
fileWatcher.Filter = "*.p*";
fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
fileWatcher.Changed += new FileSystemEventHandler(FileSystemChanged);
fileWatcher.Created += new FileSystemEventHandler(FileSystemChanged);
fileWatcher.Deleted += new FileSystemEventHandler(FileSystemChanged);
fileWatcher.EnableRaisingEvents = true;
accountsComboBox.IsEnabled = true;
ButtonRefreshModule.IsEnabled = true;
}
}
catch (Exception exception)
{
accountsComboBox.IsEnabled = true;
endBackgroundWork("Error getting account data");
UpdateStatusBox(configurationStatusTextBox, exception.StackTrace);
System.Windows.Forms.MessageBox.Show(exception.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
private void FileSystemChanged(object sender, FileSystemEventArgs e)
{
try
{
DateTime lastWriteTimeonFile = File.GetLastWriteTime(e.FullPath);
// Shorten to seconds to prevent multiple updates
String lastWriteTime = lastWriteTimeonFile.ToString("G");
if (lastWriteTime != lastUpdated)
{
lastUpdated = lastWriteTime;
Task t = new Task(delegate { refreshLocalScripts(e.FullPath); });
t.Start();
foreach (AutomationRunbook runbook in runbookListViewModel)
{
if (runbook.Name.Equals(Path.GetFileNameWithoutExtension(e.Name)))
{
runbook.LastModifiedLocal = DateTime.Now;
runbook.UpdateSyncStatus();
break;
}
}
foreach (AutomationDSC configuration in DSCListViewModel)
{
if (configuration.Name.Equals(Path.GetFileNameWithoutExtension(e.Name)))
{
configuration.LastModifiedLocal = DateTime.Now;
configuration.UpdateSyncStatus();
break;
}
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Runbook could not be refreshed.\r\nError details: " + ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
private void assetsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
setAllAssetButtonStatesTo(assetsListView.SelectedItems.Count > 0);
}
private async void assetsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
assetListViewModel.Clear();
await refreshAssets(true);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Assets could not be refreshed.\r\nError details: " + ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
private void workspaceTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
//TODO: refactor this
iseClient.baseWorkspace = workspaceTextBox.Text;
Properties.Settings.Default["localWorkspace"] = iseClient.baseWorkspace;
Properties.Settings.Default.Save();
}
private void workspaceButton_Click(object sender, RoutedEventArgs e)
{
try
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
dialog.SelectedPath = iseClient.baseWorkspace;
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
iseClient.baseWorkspace = dialog.SelectedPath;