Skip to content

Commit 372d873

Browse files
Refactor URLs and improve logging consistency (#2228)
* Refactor URLs and improve logging consistency - Use string interpolation for URLs in various methods. - Add default values for `CancellationToken` in `LoadViewAsync`. - Update logging placeholders for consistent casing in `MediaElementPage.xaml.cs`. - Switch to `Trace.TraceInformation` in `OnRowTapped`. - Enhance exception logging in `DownloadDotNetBotImage`. - Improve code readability and maintainability. * Fix strack trace issue * Switch to Trace.TraceError for error logging Updated the logging mechanism for handling exceptions across multiple files. Replaced `Trace.WriteLine` with `Trace.TraceError` in the following methods and classes: - `async Task OnAnimate(CancellationToken token)` in `AnimationBehavior.shared.cs` - `protected void OnViewPropertyChanged(object? sender, PropertyChangedEventArgs e)` in `ICommunityToolkitBehavior.shared.cs` - `protected override void OnDetachingFrom(Grid bindable)` in `ImpliedOrderGridBehavior.shared.cs` - `internal async Task ForceUpdateState(CancellationToken token, bool animated = true)` in `TouchBehavior.methods.shared.cs` - `void OnChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)` in `MultiValidationBehavior.shared.cs` - `async ValueTask UpdateStateAsync(VisualElement? view, ValidationFlags flags, bool isValid)` in `ValidationBehavior.shared.cs` - `public abstract class BaseConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]>` in `BaseConverter.shared.cs` (multiple methods) * Refactor hardcoded URIs to direct strings Disabled and restored S1075 warning across multiple files. Refactored hardcoded URIs to be directly passed as strings: - ExpanderPageCS.cs: `Launcher.OpenAsync` method - MediaElementPage.xaml.cs: media sources - FileSaverViewModel.cs: `GetStreamAsync` method - MediaElementCarouselViewViewModel.cs and MediaElementCollectionViewViewModel.cs: `ObservableCollection` initialization * Missed one $ * fix Suppresion * Improve exception logging format across multiple methods Updated logging to use formatted messages with exception details instead of directly logging stack traces. This change affects methods in ByteArrayToImageSourceConverterViewModel.cs, AnimationBehavior.shared.cs, ICommunityToolkitBehavior.shared.cs, TouchBehavior.methods.shared.cs, ValidationBehavior.shared.cs, and BaseConverter.shared.cs. Enhances log readability and debugging efficiency. * Define URLs as constant * Define URLs as constants * Use `const` to define URLs * Replace `TraceError` with `TraceInformation` --------- Co-authored-by: Brandon Minnick <13558917+brminnick@users.noreply.github.com>
1 parent 0b8f8ef commit 372d873

File tree

16 files changed

+69
-46
lines changed

16 files changed

+69
-46
lines changed

samples/CommunityToolkit.Maui.Sample/Pages/Views/Expander/ExpanderPageCS.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ public class ExpanderPageCS : ContentPage
99
{
1010
public ExpanderPageCS()
1111
{
12+
const string dotnetBotUrl = "https://avatars.githubusercontent.com/u/9011267?v=4";
13+
const string dotnetMauiUrl = "https://dot.net/maui";
14+
1215
Title = "Expander Page, C# UI";
1316

1417
Content = new VerticalStackLayout()
@@ -36,7 +39,7 @@ public ExpanderPageCS()
3639
Content = new VerticalStackLayout()
3740
{
3841
new Image()
39-
.Source("https://avatars.githubusercontent.com/u/9011267?v=4")
42+
.Source(dotnetBotUrl)
4043
.Size(120)
4144
.Aspect(Aspect.AspectFit),
4245

@@ -46,7 +49,7 @@ public ExpanderPageCS()
4649

4750
new Button()
4851
.Text("Learn more")
49-
.Invoke(button => button.Clicked += async (s, e) => await Launcher.OpenAsync("https://dot.net/maui"))
52+
.Invoke(button => button.Clicked += static async (_, _) => await Launcher.OpenAsync(dotnetMauiUrl))
5053

5154
}.Padding(10)
5255

samples/CommunityToolkit.Maui.Sample/Pages/Views/LazyView/CustomLazyView.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ namespace CommunityToolkit.Maui.Sample.Pages.Views.LazyView;
44

55
public class CustomLazyView<TView> : Maui.Views.LazyView where TView : View, new()
66
{
7-
public override async ValueTask LoadViewAsync(CancellationToken token)
7+
public override async ValueTask LoadViewAsync(CancellationToken token = default)
88
{
99
// display a loading indicator
1010
Content = new ActivityIndicator { IsRunning = true }.Center();

samples/CommunityToolkit.Maui.Sample/Pages/Views/LazyView/MyViewLazyView.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ namespace CommunityToolkit.Maui.Sample.Pages.Views.LazyView;
44

55
class MyViewLazyView : LazyView<MyView>
66
{
7-
public override async ValueTask LoadViewAsync(CancellationToken token)
7+
public override async ValueTask LoadViewAsync(CancellationToken token = default)
88
{
99
await base.LoadViewAsync(token);
1010
}

samples/CommunityToolkit.Maui.Sample/Pages/Views/MediaElement/MediaElementPage.xaml.cs

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,18 @@ namespace CommunityToolkit.Maui.Sample.Pages.Views;
1010
public partial class MediaElementPage : BasePage<MediaElementViewModel>
1111
{
1212
readonly ILogger logger;
13+
1314
const string loadOnlineMp4 = "Load Online MP4";
1415
const string loadHls = "Load HTTP Live Stream (HLS)";
1516
const string loadLocalResource = "Load Local Resource";
1617
const string resetSource = "Reset Source to null";
1718
const string loadMusic = "Load Music";
1819

20+
const string buckBunnyMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
21+
const string botImageUrl = "https://lh3.googleusercontent.com/pw/AP1GczNRrebWCJvfdIau1EbsyyYiwAfwHS0JXjbioXvHqEwYIIdCzuLodQCZmA57GADIo5iB3yMMx3t_vsefbfoHwSg0jfUjIXaI83xpiih6d-oT7qD_slR0VgNtfAwJhDBU09kS5V2T5ZML-WWZn8IrjD4J-g=w1792-h1024-s-no-gm";
22+
const string hlsStreamTestUrl = "https://mtoczko.github.io/hls-test-streams/test-gap/playlist.m3u8";
23+
const string hal9000AudioUrl = "https://github.com/prof3ssorSt3v3/media-sample-files/raw/master/hal-9000.mp3";
24+
1925
public MediaElementPage(MediaElementViewModel viewModel, ILogger<MediaElementPage> logger) : base(viewModel)
2026
{
2127
InitializeComponent();
@@ -26,9 +32,9 @@ public MediaElementPage(MediaElementViewModel viewModel, ILogger<MediaElementPag
2632

2733
void MediaElement_PropertyChanged(object? sender, PropertyChangedEventArgs e)
2834
{
29-
if (e.PropertyName == CommunityToolkit.Maui.Views.MediaElement.DurationProperty.PropertyName)
35+
if (e.PropertyName == MediaElement.DurationProperty.PropertyName)
3036
{
31-
logger.LogInformation("Duration: {newDuration}", MediaElement.Duration);
37+
logger.LogInformation("Duration: {NewDuration}", MediaElement.Duration);
3238
PositionSlider.Maximum = MediaElement.Duration.TotalSeconds;
3339
}
3440
}
@@ -44,7 +50,7 @@ void OnStateChanged(object? sender, MediaStateChangedEventArgs e) =>
4450

4551
void OnPositionChanged(object? sender, MediaPositionChangedEventArgs e)
4652
{
47-
logger.LogInformation("Position changed to {position}", e.Position);
53+
logger.LogInformation("Position changed to {Position}", e.Position);
4854
PositionSlider.Value = e.Position.TotalSeconds;
4955
}
5056

@@ -161,20 +167,17 @@ async void ChangeSourceClicked(Object sender, EventArgs e)
161167
{
162168
case loadOnlineMp4:
163169
MediaElement.MetadataTitle = "Big Buck Bunny";
164-
MediaElement.MetadataArtworkUrl = "https://lh3.googleusercontent.com/pw/AP1GczNRrebWCJvfdIau1EbsyyYiwAfwHS0JXjbioXvHqEwYIIdCzuLodQCZmA57GADIo5iB3yMMx3t_vsefbfoHwSg0jfUjIXaI83xpiih6d-oT7qD_slR0VgNtfAwJhDBU09kS5V2T5ZML-WWZn8IrjD4J-g=w1792-h1024-s-no-gm";
170+
MediaElement.MetadataArtworkUrl = botImageUrl;
165171
MediaElement.MetadataArtist = "Big Buck Bunny Album";
166172
MediaElement.Source =
167-
MediaSource.FromUri(
168-
"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4");
173+
MediaSource.FromUri(buckBunnyMp4Url);
169174
return;
170175

171176
case loadHls:
172177
MediaElement.MetadataArtist = "HLS Album";
173-
MediaElement.MetadataArtworkUrl = "https://lh3.googleusercontent.com/pw/AP1GczNRrebWCJvfdIau1EbsyyYiwAfwHS0JXjbioXvHqEwYIIdCzuLodQCZmA57GADIo5iB3yMMx3t_vsefbfoHwSg0jfUjIXaI83xpiih6d-oT7qD_slR0VgNtfAwJhDBU09kS5V2T5ZML-WWZn8IrjD4J-g=w1792-h1024-s-no-gm";
178+
MediaElement.MetadataArtworkUrl = botImageUrl;
174179
MediaElement.MetadataTitle = "HLS Title";
175-
MediaElement.Source
176-
= MediaSource.FromUri(
177-
"https://mtoczko.github.io/hls-test-streams/test-gap/playlist.m3u8");
180+
MediaElement.Source = MediaSource.FromUri(hlsStreamTestUrl);
178181
return;
179182

180183
case resetSource:
@@ -185,7 +188,7 @@ async void ChangeSourceClicked(Object sender, EventArgs e)
185188
return;
186189

187190
case loadLocalResource:
188-
MediaElement.MetadataArtworkUrl = "https://lh3.googleusercontent.com/pw/AP1GczNRrebWCJvfdIau1EbsyyYiwAfwHS0JXjbioXvHqEwYIIdCzuLodQCZmA57GADIo5iB3yMMx3t_vsefbfoHwSg0jfUjIXaI83xpiih6d-oT7qD_slR0VgNtfAwJhDBU09kS5V2T5ZML-WWZn8IrjD4J-g=w1792-h1024-s-no-gm";
191+
MediaElement.MetadataArtworkUrl = botImageUrl;
189192
MediaElement.MetadataTitle = "Local Resource Title";
190193
MediaElement.MetadataArtist = "Local Resource Album";
191194

@@ -207,19 +210,25 @@ async void ChangeSourceClicked(Object sender, EventArgs e)
207210
case loadMusic:
208211
MediaElement.MetadataTitle = "HAL 9000";
209212
MediaElement.MetadataArtist = "HAL 9000 Album";
210-
MediaElement.MetadataArtworkUrl = "https://lh3.googleusercontent.com/pw/AP1GczNRrebWCJvfdIau1EbsyyYiwAfwHS0JXjbioXvHqEwYIIdCzuLodQCZmA57GADIo5iB3yMMx3t_vsefbfoHwSg0jfUjIXaI83xpiih6d-oT7qD_slR0VgNtfAwJhDBU09kS5V2T5ZML-WWZn8IrjD4J-g=w1792-h1024-s-no-gm";
211-
MediaElement.Source = MediaSource.FromUri("https://github.com/prof3ssorSt3v3/media-sample-files/raw/master/hal-9000.mp3");
213+
MediaElement.MetadataArtworkUrl = botImageUrl;
214+
MediaElement.Source = MediaSource.FromUri(hal9000AudioUrl);
212215
return;
213216
}
214217
}
215218

216219
async void ChangeAspectClicked(object? sender, EventArgs e)
217220
{
218-
var resultAspect = await DisplayActionSheet("Choose aspect ratio",
219-
"Cancel", null, Aspect.AspectFit.ToString(),
220-
Aspect.AspectFill.ToString(), Aspect.Fill.ToString());
221+
const string cancel = "Cancel";
222+
223+
var resultAspect = await DisplayActionSheet(
224+
"Choose aspect ratio",
225+
cancel,
226+
null,
227+
Aspect.AspectFit.ToString(),
228+
Aspect.AspectFill.ToString(),
229+
Aspect.Fill.ToString());
221230

222-
if (resultAspect is null || resultAspect.Equals("Cancel"))
231+
if (resultAspect is null or cancel)
223232
{
224233
return;
225234
}
@@ -237,7 +246,7 @@ async void ChangeAspectClicked(object? sender, EventArgs e)
237246
void DisplayPopup(object sender, EventArgs e)
238247
{
239248
MediaElement.Pause();
240-
var popupMediaElement = new Maui.Views.MediaElement
249+
var popupMediaElement = new MediaElement
241250
{
242251
Source = MediaSource.FromResource("AppleVideo.mp4"),
243252
HeightRequest = 600,

samples/CommunityToolkit.Maui.Sample/ViewModels/Behaviors/TouchBehavior/TouchBehaviorCollectionViewMultipleSelectionViewModel.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,6 @@ public partial class TouchBehaviorCollectionViewMultipleSelectionViewModel : Bas
1111
[RelayCommand]
1212
void OnRowTapped(ContentCreator creatorTapped)
1313
{
14-
Trace.WriteLine($"{creatorTapped.Name} Tapped");
14+
Trace.TraceInformation($"{creatorTapped.Name} Tapped");
1515
}
1616
}

samples/CommunityToolkit.Maui.Sample/ViewModels/Converters/ByteArrayToImageSourceConverterViewModel.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,21 +44,22 @@ async Task DownloadDotNetBotImage(CancellationToken token)
4444
var maximumDownloadTime = TimeSpan.FromSeconds(5);
4545
var maximumDownloadTimeCTS = new CancellationTokenSource(maximumDownloadTime);
4646

47-
// Ensure Activity Indicator appears on screen for a minumum of 1.5 seconds when the user taps the Download Button
47+
// Ensure Activity Indicator appears on screen for a minimum of 1.5 seconds when the user taps the Download Button
4848
var minimumDownloadTime = TimeSpan.FromSeconds(1.5);
4949
var minimumDownloadTimeTask = Task.Delay(minimumDownloadTime, maximumDownloadTimeCTS.Token).WaitAsync(token);
5050

5151
try
5252
{
53-
DotNetBotImageByteArray = await client.GetByteArrayAsync("https://user-images.githubusercontent.com/13558917/137551073-ac8958bf-83e3-4ae3-8623-4db6dce49d02.png", maximumDownloadTimeCTS.Token).WaitAsync(token).ConfigureAwait(false);
53+
const string dotnetBotImageUrl = "https://user-images.githubusercontent.com/13558917/137551073-ac8958bf-83e3-4ae3-8623-4db6dce49d02.png";
54+
DotNetBotImageByteArray = await client.GetByteArrayAsync(dotnetBotImageUrl, maximumDownloadTimeCTS.Token).WaitAsync(token).ConfigureAwait(false);
5455

5556
await minimumDownloadTimeTask.ConfigureAwait(false);
5657

5758
LabelText = "The above image was downloaded as a byte[]";
5859
}
5960
catch (Exception e)
6061
{
61-
Trace.WriteLine(e);
62+
Trace.TraceError("Error downloading image: {0}", e);
6263
OnImageDownloadFailed(e.Message);
6364
}
6465
finally

samples/CommunityToolkit.Maui.Sample/ViewModels/Essentials/FileSaverViewModel.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ async Task SaveFileStatic(CancellationToken cancellationToken)
4848
async Task SaveFileInstance(CancellationToken cancellationToken)
4949
{
5050
using var client = new HttpClient();
51-
await using var stream = await client.GetStreamAsync("https://www.nuget.org/api/v2/package/CommunityToolkit.Maui/5.0.0", cancellationToken);
51+
52+
const string communityToolkitNuGetUrl = "https://www.nuget.org/api/v2/package/CommunityToolkit.Maui/5.0.0";
53+
await using var stream = await client.GetStreamAsync(communityToolkitNuGetUrl, cancellationToken);
5254
try
5355
{
5456
var fileSaverInstance = new FileSaverImplementation();

samples/CommunityToolkit.Maui.Sample/ViewModels/Views/MediaElementCarouselViewViewModel.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@ namespace CommunityToolkit.Maui.Sample.ViewModels.Views;
33

44
public partial class MediaElementCarouselViewViewModel : BaseViewModel
55
{
6+
const string buckBunnyMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
7+
const string elephantsDreamMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4";
8+
const string sintelMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4";
9+
610
public ObservableCollection<MediaElementDataSource> ItemSource { get; } =
711
[
8-
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"), "Buck Bunny", 720, 1280),
9-
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"), "Elephants Dream", 720, 1280),
10-
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4"), "Sintel", 546, 1280)
12+
new(new Uri(buckBunnyMp4Url), "Buck Bunny", 720, 1280),
13+
new(new Uri(elephantsDreamMp4Url), "Elephants Dream", 720, 1280),
14+
new(new Uri(sintelMp4Url), "Sintel", 546, 1280)
1115
];
1216
}
1317

samples/CommunityToolkit.Maui.Sample/ViewModels/Views/MediaElementCollectionViewViewModel.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@ namespace CommunityToolkit.Maui.Sample.ViewModels.Views;
33

44
public partial class MediaElementCollectionViewViewModel : BaseViewModel
55
{
6+
const string buckBunnyMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
7+
const string elephantsDreamMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4";
8+
const string sintelMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4";
9+
610
public ObservableCollection<MediaElementDataSource> ItemSource { get; } =
711
[
8-
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"), "Buck Bunny", 720, 1280),
9-
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"), "Elephants Dream", 720, 1280),
10-
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4"), "Sintel", 546, 1280)
12+
new(new Uri(buckBunnyMp4Url), "Buck Bunny", 720, 1280),
13+
new(new Uri(elephantsDreamMp4Url), "Elephants Dream", 720, 1280),
14+
new(new Uri(sintelMp4Url), "Sintel", 546, 1280)
1115
];
1216
}

src/CommunityToolkit.Maui/Behaviors/AnimationBehavior.shared.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ async Task OnAnimate(CancellationToken token)
115115
}
116116
catch (Exception ex) when (Options.ShouldSuppressExceptionsInAnimations)
117117
{
118-
Trace.WriteLine(ex);
118+
Trace.TraceInformation("{0}", ex);
119119
}
120120
}
121121
}

0 commit comments

Comments
 (0)