Skip to content

Commit 4c00bdb

Browse files
committed
Refactoring alias helper
1 parent 6cd2cff commit 4c00bdb

File tree

3 files changed

+54
-44
lines changed

3 files changed

+54
-44
lines changed

src/ResourceManager/Profile/Commands.Profile/AzureRmAlias/AliasHelper.cs

Lines changed: 48 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@
1212
// limitations under the License.
1313
// ----------------------------------------------------------------------------------
1414

15-
using Microsoft.Azure.Commands.Profile.Properties;
15+
using Microsoft.Azure.Commands.Common.Authentication;
16+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
1617
using System;
1718
using System.Collections.Generic;
18-
using System.Collections.ObjectModel;
1919
using System.IO;
2020
using System.Linq;
2121
using System.Management.Automation;
@@ -28,33 +28,47 @@ public class AliasHelper
2828
private const string STARTALIASIMPORTMARKER = "#Begin Azure PowerShell alias import";
2929
private const string ENDALIASIMPORTMARKER = "#End Azure PowerShell alias import";
3030

31+
private IDataStore _dataStore;
32+
33+
public AliasHelper(IDataStore dataStore)
34+
{
35+
_dataStore = dataStore;
36+
FileUtilities.DataStore = dataStore;
37+
}
38+
39+
public AliasHelper() : this(AzureSession.Instance.DataStore)
40+
{
41+
}
42+
3143
public static string GetProfilePath(string Scope, SessionState sessionState)
3244
{
33-
object userprofile = "";
45+
var userprofile = "";
3446
if (Scope != null && Scope.Equals("CurrentUser"))
3547
{
36-
userprofile = Path.Combine(sessionState.PSVariable.GetValue("env:USERPROFILE").ToString(), "Documents", "PowerShell", "profile.ps1");
48+
var editionType = sessionState.PSVariable.GetValue("PSEdition") as string;
49+
var psFolder = string.Equals(editionType, "Desktop", StringComparison.OrdinalIgnoreCase) ? "WindowsPowerShell" : "PowerShell";
50+
userprofile = Path.Combine(sessionState.PSVariable.GetValue("env:USERPROFILE").ToString(), "Documents", psFolder, "profile.ps1");
3751
}
3852

3953
else if (Scope != null && Scope.Equals("LocalMachine"))
4054
{
4155
userprofile = Path.Combine(sessionState.PSVariable.GetValue("PSHOME").ToString(), "profile.ps1");
4256
}
4357

44-
return userprofile.ToString();
58+
return userprofile;
4559
}
4660

47-
public static void RemoveAliasesInProfile(string userprofile, string[] Module, Dictionary<string, object> mapping)
61+
public void RemoveAliasesInProfile(string userprofile, string[] Module, Dictionary<string, object> mapping)
4862
{
4963
ParseFile(userprofile, Module, out string filecontent, out List<string> modulesToKeep, add: false);
5064

5165
// Add script to enable aliases to profile if there are any modules to keep
5266
CreateFileEntry(modulesToKeep, filecontent, userprofile, mapping);
5367
}
5468

55-
public static void AddAliasesToProfile(string userprofile, string[] Module, Dictionary<string, object> mapping)
69+
public void AddAliasesToProfile(string userprofile, string[] Module, Dictionary<string, object> mapping)
5670
{
57-
CreateProfileIfNotExisting(userprofile);
71+
CreateProfileIfNotExists(userprofile);
5872

5973
ParseFile(userprofile, Module, out string filecontent, out List<string> modulesToKeep, add: true);
6074

@@ -68,15 +82,17 @@ public static void AddAliasesToProfile(string userprofile, string[] Module, Dict
6882
}
6983
}
7084

71-
public static void ParseFile(string userprofile, string[] Module, out string filecontent, out List<string> modulesToKeep, bool add)
85+
public void ParseFile(string userprofile, string[] Module, out string filecontent, out List<string> modulesToKeep, bool add)
7286
{
7387
filecontent = "";
7488
modulesToKeep = new List<String>();
7589
if (add)
7690
{
7791
modulesToKeep = Module?.ToList();
7892
}
79-
string originalText = File.ReadAllText(userprofile.ToString());
93+
94+
95+
string originalText = _dataStore.ReadFileAsText(userprofile.ToString());
8096
if (originalText.Contains(STARTALIASIMPORTMARKER))
8197
{
8298
// Add back profile code unrelated to Azure PowerShell aliases
@@ -119,12 +135,12 @@ public static void ParseFile(string userprofile, string[] Module, out string fil
119135
}
120136
}
121137

122-
public static void CreateFileEntry(List<string> modulesToKeep, string filecontent, string userprofile, Dictionary<string, object> mapping)
138+
public void CreateFileEntry(List<string> modulesToKeep, string filecontent, string userprofile, Dictionary<string, object> mapping)
123139
{
124140
if (modulesToKeep.Count > 0)
125141
{
126142
filecontent += STARTALIASIMPORTMARKER + Environment.NewLine + "Import-Module Az.Profile -ErrorAction SilentlyContinue -ErrorVariable importError" +
127-
Environment.NewLine + "if (`$importerror.Count -eq 0) { " + Environment.NewLine;
143+
Environment.NewLine + "if ($importerror.Count -eq 0) { " + Environment.NewLine;
128144

129145
var validModules = new List<string>();
130146
foreach (var name in modulesToKeep)
@@ -139,43 +155,34 @@ public static void CreateFileEntry(List<string> modulesToKeep, string fileconten
139155
filecontent += "}" + Environment.NewLine + ENDALIASIMPORTMARKER;
140156
}
141157

142-
using (System.Management.Automation.PowerShell PowerShellInstance = System.Management.Automation.PowerShell.Create())
158+
ExecuteFileActionWithFriendlyError(() =>
143159
{
144-
PowerShellInstance.AddScript("Set-Content -Path '" + userprofile + "' -Value \"" + filecontent + "\"");
145-
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
160+
FileUtilities.EnsureDirectoryExists(Path.GetDirectoryName(userprofile));
161+
_dataStore.WriteFile(userprofile, filecontent);
162+
});
163+
}
146164

147-
// Check for error thrown when LocalMachine profile is accessed from non-admin mode.
148-
if (PowerShellInstance.Streams.Error.Count > 0)
165+
public void CreateProfileIfNotExists(string userprofile)
166+
{
167+
ExecuteFileActionWithFriendlyError(() =>
168+
{
169+
FileUtilities.EnsureDirectoryExists(Path.GetDirectoryName(userprofile));
170+
if (!_dataStore.FileExists(userprofile))
149171
{
150-
foreach (var error in PowerShellInstance.Streams.Error)
151-
{
152-
if (error.ToString().Contains("Access to the path") && error.ToString().Contains("is denied."))
153-
{
154-
throw new Exception(Resources.AliasImportFailure);
155-
}
156-
}
172+
_dataStore.WriteFile(userprofile, Environment.NewLine);
157173
}
158-
}
174+
});
159175
}
160176

161-
public static void CreateProfileIfNotExisting(string userprofile)
177+
private static void ExecuteFileActionWithFriendlyError(Action fileAction)
162178
{
163-
using (System.Management.Automation.PowerShell PowerShellInstance = System.Management.Automation.PowerShell.Create())
179+
try
164180
{
165-
PowerShellInstance.AddScript("if (!(Test-Path '" + userprofile + "')) { New-Item '" + userprofile + "' -ItemType file -Force }");
166-
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
167-
168-
// Check for error thrown when LocalMachine profile is accessed from non-admin mode.
169-
if (PowerShellInstance.Streams.Error.Count > 0)
170-
{
171-
foreach (var error in PowerShellInstance.Streams.Error)
172-
{
173-
if (error.ToString().Contains("Access to the path") && error.ToString().Contains("is denied."))
174-
{
175-
throw new Exception(Resources.AliasImportFailure);
176-
}
177-
}
178-
}
181+
fileAction();
182+
}
183+
catch (UnauthorizedAccessException accessException) when (accessException?.Message != null && accessException.Message.ToLower().Contains("denied"))
184+
{
185+
throw new UnauthorizedAccessException(Properties.Resources.AliasImportFailure, accessException);
179186
}
180187
}
181188
}

src/ResourceManager/Profile/Commands.Profile/AzureRmAlias/DisableAzureRmAlias.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
// limitations under the License.
1313
// ----------------------------------------------------------------------------------
1414

15+
using Microsoft.Azure.Commands.Common.Authentication;
1516
using Microsoft.Azure.Commands.ResourceManager.Common;
1617
using Newtonsoft.Json;
1718
using System;
@@ -58,9 +59,10 @@ public override void ExecuteCmdlet()
5859

5960
if (Scope != null && (Scope.Equals("CurrentUser") || Scope.Equals("LocalMachine")))
6061
{
61-
if (File.Exists(userprofile.ToString()))
62+
if (AzureSession.Instance.DataStore.FileExists(userprofile))
6263
{
63-
AliasHelper.RemoveAliasesInProfile(userprofile, Module, mapping);
64+
var helper = new AliasHelper();
65+
helper.RemoveAliasesInProfile(userprofile, Module, mapping);
6466
}
6567
}
6668
}

src/ResourceManager/Profile/Commands.Profile/AzureRmAlias/EnableAzureRmAlias.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ public override void ExecuteCmdlet()
5858

5959
if (Scope != null && (Scope.Equals("CurrentUser") || Scope.Equals("LocalMachine")))
6060
{
61-
AliasHelper.AddAliasesToProfile(userprofile, Module, mapping);
61+
var helper = new AliasHelper();
62+
helper.AddAliasesToProfile(userprofile, Module, mapping);
6263
}
6364
}
6465

0 commit comments

Comments
 (0)