-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathMainViewModel.cs
262 lines (214 loc) · 9.17 KB
/
MainViewModel.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
using System.Diagnostics;
using System.Net;
using System.Text;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.WinUI.UI.Controls;
using Microsoft.Graph.Models;
using Microsoft.Graph.Models.ODataErrors;
using Microsoft.Kiota.Abstractions;
using MsGraphSamples.Services;
using MsGraphSamples.WinUI.Helpers;
using System.Collections.Immutable;
using System.Reflection;
namespace MsGraphSamples.WinUI.ViewModels;
public partial class MainViewModel(
IAuthService authService,
IAsyncEnumerableGraphDataService graphDataService,
IDialogService dialogService) : ObservableRecipient
{
public ushort PageSize { get; set; } = 25;
private readonly Stopwatch _stopWatch = new();
public long ElapsedMs => _stopWatch.ElapsedMilliseconds;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsIndeterminate))]
private bool _isBusy = false;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsIndeterminate))]
private bool _isError = false;
public bool IsIndeterminate => IsBusy || IsError;
[ObservableProperty]
private string? _userName;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(LaunchGraphExplorerCommand))]
[NotifyPropertyChangedFor(nameof(LastUrl))]
[NotifyPropertyChangedFor(nameof(LastCount))]
private AsyncLoadingCollection<DirectoryObject>? _directoryObjects;
[ObservableProperty]
private DirectoryObject? _selectedObject;
public static IReadOnlyList<string> Entities => ["Users", "Groups", "Applications", "ServicePrincipals", "Devices"];
[ObservableProperty]
private string _selectedEntity = "Users";
public string? LastUrl => graphDataService.LastUrl;
public long? LastCount => graphDataService.LastCount;
#region OData Operators
public string[] SplittedSelect => Select.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
[ObservableProperty]
public string _select = "id,displayName,mail,userPrincipalName";
[ObservableProperty]
public string? _filter;
public string[]? SplittedOrderBy => OrderBy?.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
[ObservableProperty]
public string? _orderBy;
private string? _search;
public string? Search
{
get => _search;
set
{
if (_search != value)
{
_search = FixSearchSyntax(value);
OnPropertyChanged();
}
}
}
private static string? FixSearchSyntax(string? searchValue)
{
if (searchValue == null)
return null;
if (searchValue.Contains('"'))
return searchValue; // Assume already correctly formatted
var elements = searchValue.Trim().Split(' ');
var sb = new StringBuilder(elements.Length);
foreach (var element in elements)
{
string? newElement;
if (element.Contains(':'))
newElement = $"\"{element}\""; // Search clause needs to be wrapped by double quotes
else if (element.In("AND", "OR"))
newElement = $" {element.ToUpperInvariant()} "; // [AND, OR] Operators need to be uppercase
else
newElement = element;
sb.Append(newElement);
}
return sb.ToString();
}
#endregion
public async Task PageLoaded()
{
var user = await graphDataService.GetUserAsync(["displayName"]);
UserName = user?.DisplayName;
await Load();
}
[RelayCommand]
private Task Load()
{
return IsBusyWrapper(SelectedEntity switch
{
//"Users" => _graphDataService.GetUsersInBatch(SplittedSelect, pageSize),
"Users" => graphDataService.GetUsers(SplittedSelect, Filter, SplittedOrderBy, Search, PageSize),
"Groups" => graphDataService.GetGroups(SplittedSelect, Filter, SplittedOrderBy, Search, PageSize),
"Applications" => graphDataService.GetApplications(SplittedSelect, Filter, SplittedOrderBy, Search, PageSize),
"ServicePrincipals" => graphDataService.GetServicePrincipals(SplittedSelect, Filter, SplittedOrderBy, Search, PageSize),
"Devices" => graphDataService.GetDevices(SplittedSelect, Filter, SplittedOrderBy, Search, PageSize),
_ => throw new NotImplementedException("Can't find selected entity")
});
}
public Task DrillDown()
{
ArgumentNullException.ThrowIfNull(SelectedObject);
OrderBy = null;
Filter = null;
Search = null;
return IsBusyWrapper(SelectedEntity switch
{
"Users" => graphDataService.GetTransitiveMemberOfAsGroups(SelectedObject.Id!, SplittedSelect, PageSize),
"Groups" => graphDataService.GetTransitiveMembersAsUsers(SelectedObject.Id!, SplittedSelect, PageSize),
"Applications" => graphDataService.GetApplicationOwnersAsUsers(SelectedObject.Id!, SplittedSelect, PageSize),
"ServicePrincipals" => graphDataService.GetServicePrincipalOwnersAsUsers(SelectedObject.Id!, SplittedSelect, PageSize),
"Devices" => graphDataService.GetDeviceOwnersAsUsers(SelectedObject.Id!, SplittedSelect, PageSize),
_ => throw new NotImplementedException("Can't find selected entity")
});
}
public Task Sort(object sender, DataGridColumnEventArgs e)
{
OrderBy = e.Column.SortDirection == null || e.Column.SortDirection == DataGridSortDirection.Descending
? $"{e.Column.Header} asc"
: $"{e.Column.Header} desc";
return Load();
}
private bool CanLaunchGraphExplorer() => LastUrl is not null;
[RelayCommand(CanExecute = nameof(CanLaunchGraphExplorer))]
private void LaunchGraphExplorer()
{
ArgumentNullException.ThrowIfNull(LastUrl);
var geBaseUrl = "https://developer.microsoft.com/en-us/graph/graph-explorer";
var graphUrl = "https://graph.microsoft.com";
var version = "v1.0";
var startOfQuery = LastUrl.NthIndexOf('/', 4) + 1;
var encodedUrl = WebUtility.UrlEncode(LastUrl[startOfQuery..]);
var encodedHeaders = "W3sibmFtZSI6IkNvbnNpc3RlbmN5TGV2ZWwiLCJ2YWx1ZSI6ImV2ZW50dWFsIn1d"; // ConsistencyLevel = eventual
var url = $"{geBaseUrl}?request={encodedUrl}&method=GET&version={version}&GraphUrl={graphUrl}&headers={encodedHeaders}";
var psi = new ProcessStartInfo { FileName = url, UseShellExecute = true };
System.Diagnostics.Process.Start(psi);
}
[RelayCommand]
private void Logout()
{
authService.Logout();
App.Current.Exit();
}
private async Task IsBusyWrapper(IAsyncEnumerable<DirectoryObject> directoryObjects)
{
IsError = false;
IsBusy = true;
_stopWatch.Restart();
try
{
// Sending message to generate DataGridColumns according to the selected properties
await GetPropertiesAndSortDirection(directoryObjects);
DirectoryObjects = new(directoryObjects, PageSize);
// Trigger load due to bug https://github.com/CommunityToolkit/WindowsCommunityToolkit/issues/3584
await DirectoryObjects.RefreshAsync();
SelectedEntity = DirectoryObjects.FirstOrDefault() switch
{
User => "Users",
Group => "Groups",
Application => "Applications",
ServicePrincipal => "ServicePrincipals",
Device => "Devices",
_ => SelectedEntity,
};
}
catch (ODataError ex)
{
IsError = true;
await dialogService.ShowAsync(ex.Error?.Code ?? "OData Error", ex.Error?.Message);
}
catch (ApiException ex)
{
IsError = true;
await dialogService.ShowAsync(Enum.GetName((HttpStatusCode)ex.ResponseStatusCode)!, ex.Message);
}
finally
{
_stopWatch.Stop();
OnPropertyChanged(nameof(ElapsedMs));
IsBusy = false;
}
}
private async Task GetPropertiesAndSortDirection(IAsyncEnumerable<DirectoryObject> directoryObjects)
{
var item = await directoryObjects.FirstOrDefaultAsync();
if (item == null)
return;
var propertiesAndSortDirection = item.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => p.Name)
.Where(p => p.In(SplittedSelect))
.ToImmutableSortedDictionary(kv => kv, GetSortDirection);
WeakReferenceMessenger.Default.Send(propertiesAndSortDirection);
DataGridSortDirection? GetSortDirection(string propertyName)
{
var property = OrderBy?.Split(' ')[0];
var direction = OrderBy?.Split(' ').ElementAtOrDefault(1) ?? "asc";
if (propertyName.Equals(property, StringComparison.InvariantCultureIgnoreCase))
return direction.Equals("asc", StringComparison.InvariantCultureIgnoreCase)
? DataGridSortDirection.Ascending
: DataGridSortDirection.Descending;
return null;
}
}
}