Skip to content

Commit

Permalink
Refactor URLs and improve logging consistency (#2228)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
ne0rrmatrix and brminnick authored Oct 1, 2024
1 parent 0b8f8ef commit 372d873
Show file tree
Hide file tree
Showing 16 changed files with 69 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ public class ExpanderPageCS : ContentPage
{
public ExpanderPageCS()
{
const string dotnetBotUrl = "https://avatars.githubusercontent.com/u/9011267?v=4";
const string dotnetMauiUrl = "https://dot.net/maui";

Title = "Expander Page, C# UI";

Content = new VerticalStackLayout()
Expand Down Expand Up @@ -36,7 +39,7 @@ public ExpanderPageCS()
Content = new VerticalStackLayout()
{
new Image()
.Source("https://avatars.githubusercontent.com/u/9011267?v=4")
.Source(dotnetBotUrl)
.Size(120)
.Aspect(Aspect.AspectFit),

Expand All @@ -46,7 +49,7 @@ public ExpanderPageCS()

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

}.Padding(10)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace CommunityToolkit.Maui.Sample.Pages.Views.LazyView;

public class CustomLazyView<TView> : Maui.Views.LazyView where TView : View, new()
{
public override async ValueTask LoadViewAsync(CancellationToken token)
public override async ValueTask LoadViewAsync(CancellationToken token = default)
{
// display a loading indicator
Content = new ActivityIndicator { IsRunning = true }.Center();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace CommunityToolkit.Maui.Sample.Pages.Views.LazyView;

class MyViewLazyView : LazyView<MyView>
{
public override async ValueTask LoadViewAsync(CancellationToken token)
public override async ValueTask LoadViewAsync(CancellationToken token = default)
{
await base.LoadViewAsync(token);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ namespace CommunityToolkit.Maui.Sample.Pages.Views;
public partial class MediaElementPage : BasePage<MediaElementViewModel>
{
readonly ILogger logger;

const string loadOnlineMp4 = "Load Online MP4";
const string loadHls = "Load HTTP Live Stream (HLS)";
const string loadLocalResource = "Load Local Resource";
const string resetSource = "Reset Source to null";
const string loadMusic = "Load Music";

const string buckBunnyMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
const string botImageUrl = "https://lh3.googleusercontent.com/pw/AP1GczNRrebWCJvfdIau1EbsyyYiwAfwHS0JXjbioXvHqEwYIIdCzuLodQCZmA57GADIo5iB3yMMx3t_vsefbfoHwSg0jfUjIXaI83xpiih6d-oT7qD_slR0VgNtfAwJhDBU09kS5V2T5ZML-WWZn8IrjD4J-g=w1792-h1024-s-no-gm";
const string hlsStreamTestUrl = "https://mtoczko.github.io/hls-test-streams/test-gap/playlist.m3u8";
const string hal9000AudioUrl = "https://github.com/prof3ssorSt3v3/media-sample-files/raw/master/hal-9000.mp3";

public MediaElementPage(MediaElementViewModel viewModel, ILogger<MediaElementPage> logger) : base(viewModel)
{
InitializeComponent();
Expand All @@ -26,9 +32,9 @@ public MediaElementPage(MediaElementViewModel viewModel, ILogger<MediaElementPag

void MediaElement_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == CommunityToolkit.Maui.Views.MediaElement.DurationProperty.PropertyName)
if (e.PropertyName == MediaElement.DurationProperty.PropertyName)
{
logger.LogInformation("Duration: {newDuration}", MediaElement.Duration);
logger.LogInformation("Duration: {NewDuration}", MediaElement.Duration);
PositionSlider.Maximum = MediaElement.Duration.TotalSeconds;
}
}
Expand All @@ -44,7 +50,7 @@ void OnStateChanged(object? sender, MediaStateChangedEventArgs e) =>

void OnPositionChanged(object? sender, MediaPositionChangedEventArgs e)
{
logger.LogInformation("Position changed to {position}", e.Position);
logger.LogInformation("Position changed to {Position}", e.Position);
PositionSlider.Value = e.Position.TotalSeconds;
}

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

case loadHls:
MediaElement.MetadataArtist = "HLS Album";
MediaElement.MetadataArtworkUrl = "https://lh3.googleusercontent.com/pw/AP1GczNRrebWCJvfdIau1EbsyyYiwAfwHS0JXjbioXvHqEwYIIdCzuLodQCZmA57GADIo5iB3yMMx3t_vsefbfoHwSg0jfUjIXaI83xpiih6d-oT7qD_slR0VgNtfAwJhDBU09kS5V2T5ZML-WWZn8IrjD4J-g=w1792-h1024-s-no-gm";
MediaElement.MetadataArtworkUrl = botImageUrl;
MediaElement.MetadataTitle = "HLS Title";
MediaElement.Source
= MediaSource.FromUri(
"https://mtoczko.github.io/hls-test-streams/test-gap/playlist.m3u8");
MediaElement.Source = MediaSource.FromUri(hlsStreamTestUrl);
return;

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

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

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

async void ChangeAspectClicked(object? sender, EventArgs e)
{
var resultAspect = await DisplayActionSheet("Choose aspect ratio",
"Cancel", null, Aspect.AspectFit.ToString(),
Aspect.AspectFill.ToString(), Aspect.Fill.ToString());
const string cancel = "Cancel";

var resultAspect = await DisplayActionSheet(
"Choose aspect ratio",
cancel,
null,
Aspect.AspectFit.ToString(),
Aspect.AspectFill.ToString(),
Aspect.Fill.ToString());

if (resultAspect is null || resultAspect.Equals("Cancel"))
if (resultAspect is null or cancel)
{
return;
}
Expand All @@ -237,7 +246,7 @@ async void ChangeAspectClicked(object? sender, EventArgs e)
void DisplayPopup(object sender, EventArgs e)
{
MediaElement.Pause();
var popupMediaElement = new Maui.Views.MediaElement
var popupMediaElement = new MediaElement
{
Source = MediaSource.FromResource("AppleVideo.mp4"),
HeightRequest = 600,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ public partial class TouchBehaviorCollectionViewMultipleSelectionViewModel : Bas
[RelayCommand]
void OnRowTapped(ContentCreator creatorTapped)
{
Trace.WriteLine($"{creatorTapped.Name} Tapped");
Trace.TraceInformation($"{creatorTapped.Name} Tapped");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,22 @@ async Task DownloadDotNetBotImage(CancellationToken token)
var maximumDownloadTime = TimeSpan.FromSeconds(5);
var maximumDownloadTimeCTS = new CancellationTokenSource(maximumDownloadTime);

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

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

await minimumDownloadTimeTask.ConfigureAwait(false);

LabelText = "The above image was downloaded as a byte[]";
}
catch (Exception e)
{
Trace.WriteLine(e);
Trace.TraceError("Error downloading image: {0}", e);
OnImageDownloadFailed(e.Message);
}
finally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ async Task SaveFileStatic(CancellationToken cancellationToken)
async Task SaveFileInstance(CancellationToken cancellationToken)
{
using var client = new HttpClient();
await using var stream = await client.GetStreamAsync("https://www.nuget.org/api/v2/package/CommunityToolkit.Maui/5.0.0", cancellationToken);

const string communityToolkitNuGetUrl = "https://www.nuget.org/api/v2/package/CommunityToolkit.Maui/5.0.0";
await using var stream = await client.GetStreamAsync(communityToolkitNuGetUrl, cancellationToken);
try
{
var fileSaverInstance = new FileSaverImplementation();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ namespace CommunityToolkit.Maui.Sample.ViewModels.Views;

public partial class MediaElementCarouselViewViewModel : BaseViewModel
{
const string buckBunnyMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
const string elephantsDreamMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4";
const string sintelMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4";

public ObservableCollection<MediaElementDataSource> ItemSource { get; } =
[
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"), "Buck Bunny", 720, 1280),
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"), "Elephants Dream", 720, 1280),
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4"), "Sintel", 546, 1280)
new(new Uri(buckBunnyMp4Url), "Buck Bunny", 720, 1280),
new(new Uri(elephantsDreamMp4Url), "Elephants Dream", 720, 1280),
new(new Uri(sintelMp4Url), "Sintel", 546, 1280)
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ namespace CommunityToolkit.Maui.Sample.ViewModels.Views;

public partial class MediaElementCollectionViewViewModel : BaseViewModel
{
const string buckBunnyMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
const string elephantsDreamMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4";
const string sintelMp4Url = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4";

public ObservableCollection<MediaElementDataSource> ItemSource { get; } =
[
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"), "Buck Bunny", 720, 1280),
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"), "Elephants Dream", 720, 1280),
new(new Uri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4"), "Sintel", 546, 1280)
new(new Uri(buckBunnyMp4Url), "Buck Bunny", 720, 1280),
new(new Uri(elephantsDreamMp4Url), "Elephants Dream", 720, 1280),
new(new Uri(sintelMp4Url), "Sintel", 546, 1280)
];
}
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async Task OnAnimate(CancellationToken token)
}
catch (Exception ex) when (Options.ShouldSuppressExceptionsInAnimations)
{
Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ protected void OnViewPropertyChanged(object? sender, PropertyChangedEventArgs e)
}
catch (Exception ex) when (Options.ShouldSuppressExceptionsInBehaviors)
{
Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ protected override void OnDetachingFrom(Grid bindable)

static void LogWarning(string warning, bool shouldThrowException)
{
System.Diagnostics.Trace.WriteLine(warning);
System.Diagnostics.Trace.TraceWarning(warning);

if (shouldThrowException)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ internal async Task ForceUpdateState(CancellationToken token, bool animated = tr
}
catch (TaskCanceledException ex)
{
Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ await Task.WhenAll(children.Select(c =>
return c.ValidateNestedAsync(token).AsTask();
})).ConfigureAwait(false);

var errors = children.Where(c => c.IsNotValid).Select(GetError).ToList();
var errors = children.Where(static c => c.IsNotValid).Select(GetError).ToList();

if (!errors.Any())
if (errors.Count is 0)
{
Errors = null;
return true;
Expand All @@ -82,7 +82,7 @@ await Task.WhenAll(children.Select(c =>
return false;
}

void OnChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
static void OnChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems is not null)
{
Expand All @@ -91,7 +91,7 @@ void OnChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArg
var isSuccessful = ((ICommunityToolkitBehavior<VisualElement>)child).TrySetBindingContextToAttachedViewBindingContext();
if (!isSuccessful)
{
Trace.WriteLine($"Setting {nameof(BindingContext)} for {child.GetType()} failed");
Trace.TraceInformation($"Setting {nameof(BindingContext)} for {child.GetType()} failed");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ async ValueTask UpdateStateAsync(VisualElement? view, ValidationFlags flags, boo
IsValid = false;
IsRunning = false;

Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/CommunityToolkit.Maui/Converters/BaseConverter.shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public abstract class BaseConverter<[DynamicallyAccessedMembers(DynamicallyAcces
}
catch (Exception ex) when (Options.ShouldSuppressExceptionsInConverters)
{
Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
return DefaultConvertBackReturnValue;
}
}
Expand All @@ -92,7 +92,7 @@ public abstract class BaseConverter<[DynamicallyAccessedMembers(DynamicallyAcces
}
catch (Exception ex) when (Options.ShouldSuppressExceptionsInConverters)
{
Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
return DefaultConvertReturnValue;
}
}
Expand Down Expand Up @@ -157,7 +157,7 @@ public abstract class BaseConverter<[DynamicallyAccessedMembers(DynamicallyAcces
}
catch (Exception ex) when (Options.ShouldSuppressExceptionsInConverters)
{
Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
return DefaultConvertBackReturnValue;
}
}
Expand All @@ -175,7 +175,7 @@ public abstract class BaseConverter<[DynamicallyAccessedMembers(DynamicallyAcces
}
catch (Exception ex) when (Options.ShouldSuppressExceptionsInConverters)
{
Trace.WriteLine(ex);
Trace.TraceInformation("{0}", ex);
return DefaultConvertReturnValue;
}
}
Expand Down

0 comments on commit 372d873

Please sign in to comment.