From d66816df2abcc8f6a223cad3f7e59aab6133160a Mon Sep 17 00:00:00 2001 From: Shane32 Date: Tue, 4 Jun 2024 23:27:08 -0400 Subject: [PATCH] Misc cleanup --- .editorconfig | 2 +- .github/workflows/wf-verify-formatting.yml | 2 +- QRCoder/Base64QRCode.cs | 10 +- QRCoder/PayloadGenerator/Geolocation.cs | 13 +- QRCoder/PayloadGenerator/MMS.cs | 24 +--- QRCoder/PayloadGenerator/Mail.cs | 13 +- QRCoder/PayloadGenerator/OneTimePassword.cs | 13 +- QRCoder/PayloadGenerator/SMS.cs | 28 +--- QRCoder/PayloadGenerator/SkypeCall.cs | 5 +- QRCoder/PayloadGenerator/Url.cs | 5 +- QRCoder/SvgQRCode.cs | 67 +++------- QRCoderConsole/Program.cs | 19 ++- QRCoderDemo/Form1.cs | 18 +-- QRCoderDemoUWP/App.xaml.cs | 135 ++++++++++---------- QRCoderDemoUWP/MainPage.xaml.cs | 95 +++++++------- 15 files changed, 176 insertions(+), 273 deletions(-) diff --git a/.editorconfig b/.editorconfig index e968d1ff..a4c561f8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -90,7 +90,7 @@ csharp_style_var_elsewhere = true:suggestion # C# code style settings - Expression-bodied members # https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-language-conventions?view=vs-2019#expression-bodied-members -csharp_style_expression_bodied_methods = when_on_single_line:suggestion +csharp_style_expression_bodied_methods = when_on_single_line:warning csharp_style_expression_bodied_constructors = false:warning csharp_style_expression_bodied_operators = when_on_single_line:warning csharp_style_expression_bodied_properties = when_on_single_line:warning diff --git a/.github/workflows/wf-verify-formatting.yml b/.github/workflows/wf-verify-formatting.yml index ae221c10..acc21c54 100644 --- a/.github/workflows/wf-verify-formatting.yml +++ b/.github/workflows/wf-verify-formatting.yml @@ -24,5 +24,5 @@ jobs: - name: Restore NuGet Packages run: dotnet restore - - name: Format QRCoder + - name: Format solution run: dotnet format --verify-no-changes --severity error diff --git a/QRCoder/Base64QRCode.cs b/QRCoder/Base64QRCode.cs index 4d4b111b..8a522489 100644 --- a/QRCoder/Base64QRCode.cs +++ b/QRCoder/Base64QRCode.cs @@ -149,7 +149,6 @@ public string GetGraphic(int pixelsPerModule, Color darkColor, Color lightColor, #endif private string BitmapToBase64(Bitmap bmp, ImageType imgType) { - var base64 = string.Empty; var iFormat = imgType switch { ImageType.Png => ImageFormat.Png, @@ -157,12 +156,9 @@ private string BitmapToBase64(Bitmap bmp, ImageType imgType) ImageType.Gif => ImageFormat.Gif, _ => ImageFormat.Png, }; - using (var memoryStream = new MemoryStream()) - { - bmp.Save(memoryStream, iFormat); - base64 = Convert.ToBase64String(memoryStream.ToArray(), Base64FormattingOptions.None); - } - return base64; + using var memoryStream = new MemoryStream(); + bmp.Save(memoryStream, iFormat); + return Convert.ToBase64String(memoryStream.ToArray(), Base64FormattingOptions.None); } #endif diff --git a/QRCoder/PayloadGenerator/Geolocation.cs b/QRCoder/PayloadGenerator/Geolocation.cs index b36cb40a..944eef1d 100644 --- a/QRCoder/PayloadGenerator/Geolocation.cs +++ b/QRCoder/PayloadGenerator/Geolocation.cs @@ -28,15 +28,12 @@ public Geolocation(string latitude, string longitude, GeolocationEncoding encodi /// Returns a string representation of the geolocation payload. /// /// A string representation of the geolocation payload in the specified encoding format. - public override string ToString() + public override string ToString() => _encoding switch { - return _encoding switch - { - GeolocationEncoding.GEO => $"geo:{_latitude},{_longitude}", - GeolocationEncoding.GoogleMaps => $"http://maps.google.com/maps?q={_latitude},{_longitude}", - _ => "geo:", - }; - } + GeolocationEncoding.GEO => $"geo:{_latitude},{_longitude}", + GeolocationEncoding.GoogleMaps => $"http://maps.google.com/maps?q={_latitude},{_longitude}", + _ => "geo:", + }; /// /// Defines the encoding types for geolocation payloads. diff --git a/QRCoder/PayloadGenerator/MMS.cs b/QRCoder/PayloadGenerator/MMS.cs index 65edad87..f4ccdfb7 100644 --- a/QRCoder/PayloadGenerator/MMS.cs +++ b/QRCoder/PayloadGenerator/MMS.cs @@ -41,26 +41,12 @@ public MMS(string number, string subject, MMSEncoding encoding = MMSEncoding.MMS /// Returns the MMS payload as a string. /// /// The MMS payload as a string. - public override string ToString() + public override string ToString() => _encoding switch { - var returnVal = string.Empty; - switch (_encoding) - { - case MMSEncoding.MMSTO: - var queryStringMmsTo = string.Empty; - if (!string.IsNullOrEmpty(_subject)) - queryStringMmsTo = $"?subject={Uri.EscapeDataString(_subject)}"; - returnVal = $"mmsto:{_number}{queryStringMmsTo}"; - break; - case MMSEncoding.MMS: - var queryStringMms = string.Empty; - if (!string.IsNullOrEmpty(_subject)) - queryStringMms = $"?body={Uri.EscapeDataString(_subject)}"; - returnVal = $"mms:{_number}{queryStringMms}"; - break; - } - return returnVal; - } + MMSEncoding.MMSTO => $"mmsto:{_number}{(string.IsNullOrEmpty(_subject) ? string.Empty : $"?subject={Uri.EscapeDataString(_subject)}")}", + MMSEncoding.MMS => $"mms:{_number}{(string.IsNullOrEmpty(_subject) ? string.Empty : $"?body={Uri.EscapeDataString(_subject)}")}", + _ => string.Empty, + }; /// /// Defines the encoding types for the MMS payload. diff --git a/QRCoder/PayloadGenerator/Mail.cs b/QRCoder/PayloadGenerator/Mail.cs index 0f911ebb..82bcaa92 100644 --- a/QRCoder/PayloadGenerator/Mail.cs +++ b/QRCoder/PayloadGenerator/Mail.cs @@ -36,7 +36,6 @@ public Mail(string? mailReceiver = null, string? subject = null, string? message /// The email payload as a string. public override string ToString() { - var returnVal = string.Empty; switch (_encoding) { case MailEncoding.MAILTO: @@ -46,16 +45,14 @@ public override string ToString() if (!string.IsNullOrEmpty(_message)) parts.Add("body=" + Uri.EscapeDataString(_message)); var queryString = parts.Any() ? $"?{string.Join("&", parts.ToArray())}" : ""; - returnVal = $"mailto:{_mailReceiver}{queryString}"; - break; + return $"mailto:{_mailReceiver}{queryString}"; case MailEncoding.MATMSG: - returnVal = $"MATMSG:TO:{_mailReceiver};SUB:{EscapeInput(_subject ?? "")};BODY:{EscapeInput(_message ?? "")};;"; - break; + return $"MATMSG:TO:{_mailReceiver};SUB:{EscapeInput(_subject ?? "")};BODY:{EscapeInput(_message ?? "")};;"; case MailEncoding.SMTP: - returnVal = $"SMTP:{_mailReceiver}:{EscapeInput(_subject ?? "", true)}:{EscapeInput(_message ?? "", true)}"; - break; + return $"SMTP:{_mailReceiver}:{EscapeInput(_subject ?? "", true)}:{EscapeInput(_message ?? "", true)}"; + default: + return string.Empty; } - return returnVal; } /// diff --git a/QRCoder/PayloadGenerator/OneTimePassword.cs b/QRCoder/PayloadGenerator/OneTimePassword.cs index 94f77c53..5cda93db 100644 --- a/QRCoder/PayloadGenerator/OneTimePassword.cs +++ b/QRCoder/PayloadGenerator/OneTimePassword.cs @@ -96,15 +96,12 @@ public enum OoneTimePasswordAuthAlgorithm /// Returns the OTP payload as a string. /// /// The OTP payload as a string. - public override string ToString() + public override string ToString() => Type switch { - return Type switch - { - OneTimePasswordAuthType.TOTP => TimeToString(), - OneTimePasswordAuthType.HOTP => HMACToString(), - _ => throw new ArgumentOutOfRangeException(), - }; - } + OneTimePasswordAuthType.TOTP => TimeToString(), + OneTimePasswordAuthType.HOTP => HMACToString(), + _ => throw new ArgumentOutOfRangeException(), + }; // Note: Issuer:Label must only contain 1 : if either of the Issuer or the Label has a : then it is invalid. // Defaults are 6 digits and 30 for Period diff --git a/QRCoder/PayloadGenerator/SMS.cs b/QRCoder/PayloadGenerator/SMS.cs index 48894b0f..62af2849 100644 --- a/QRCoder/PayloadGenerator/SMS.cs +++ b/QRCoder/PayloadGenerator/SMS.cs @@ -41,29 +41,13 @@ public SMS(string number, string subject, SMSEncoding encoding = SMSEncoding.SMS /// Returns the SMS payload as a string. /// /// The SMS payload as a string. - public override string ToString() + public override string ToString() => _encoding switch { - var returnVal = string.Empty; - switch (_encoding) - { - case SMSEncoding.SMS: - var queryString = string.Empty; - if (!string.IsNullOrEmpty(_subject)) - queryString = $"?body={Uri.EscapeDataString(_subject)}"; - returnVal = $"sms:{_number}{queryString}"; - break; - case SMSEncoding.SMS_iOS: - var queryStringiOS = string.Empty; - if (!string.IsNullOrEmpty(_subject)) - queryStringiOS = $";body={Uri.EscapeDataString(_subject)}"; - returnVal = $"sms:{_number}{queryStringiOS}"; - break; - case SMSEncoding.SMSTO: - returnVal = $"SMSTO:{_number}:{_subject}"; - break; - } - return returnVal; - } + SMSEncoding.SMS => $"sms:{_number}{(string.IsNullOrEmpty(_subject) ? string.Empty : $"?body={Uri.EscapeDataString(_subject)}")}", + SMSEncoding.SMS_iOS => $"sms:{_number}{(string.IsNullOrEmpty(_subject) ? string.Empty : $";body={Uri.EscapeDataString(_subject)}")}", + SMSEncoding.SMSTO => $"SMSTO:{_number}:{_subject}", + _ => string.Empty, + }; /// /// Specifies the encoding type for the SMS payload. diff --git a/QRCoder/PayloadGenerator/SkypeCall.cs b/QRCoder/PayloadGenerator/SkypeCall.cs index 0f934ffa..1df3d91d 100644 --- a/QRCoder/PayloadGenerator/SkypeCall.cs +++ b/QRCoder/PayloadGenerator/SkypeCall.cs @@ -22,9 +22,6 @@ public SkypeCall(string skypeUsername) /// Converts the Skype call payload to a string. /// /// A string representation of the Skype call payload. - public override string ToString() - { - return $"skype:{_skypeUsername}?call"; - } + public override string ToString() => $"skype:{_skypeUsername}?call"; } } diff --git a/QRCoder/PayloadGenerator/Url.cs b/QRCoder/PayloadGenerator/Url.cs index 356f55e1..14617e3e 100644 --- a/QRCoder/PayloadGenerator/Url.cs +++ b/QRCoder/PayloadGenerator/Url.cs @@ -24,9 +24,6 @@ public Url(string url) /// Returns the URL payload as a string. /// /// The URL payload as a string, ensuring it starts with "http://" if no protocol is specified. - public override string ToString() - { - return (!_url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? "http://" + _url : _url); - } + public override string ToString() => !_url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? "http://" + _url : _url; } } diff --git a/QRCoder/SvgQRCode.cs b/QRCoder/SvgQRCode.cs index a0cd0933..af668fb8 100644 --- a/QRCoder/SvgQRCode.cs +++ b/QRCoder/SvgQRCode.cs @@ -1,10 +1,7 @@ #if !NETSTANDARD1_3 using System; -using System.Collections; -using System.Collections.Generic; using System.Drawing; using System.Text; -using System.Text.RegularExpressions; using QRCoder.Extensions; using static QRCoder.QRCodeGenerator; using static QRCoder.SvgQRCode; @@ -84,9 +81,7 @@ public string GetGraphic(int pixelsPerModule, string darkColorHex, string lightC /// An optional logo to be rendered on the code (either Bitmap or SVG). /// Returns the QR code graphic as an SVG string. public string GetGraphic(Size viewBox, bool drawQuietZones = true, SizingMode sizingMode = SizingMode.WidthHeightAttribute, SvgLogo? logo = null) - { - return GetGraphic(viewBox, Color.Black, Color.White, drawQuietZones, sizingMode, logo); - } + => GetGraphic(viewBox, Color.Black, Color.White, drawQuietZones, sizingMode, logo); /// /// Returns a QR code as an SVG string with custom colors and optional quiet zones and an optional logo. @@ -99,9 +94,7 @@ public string GetGraphic(Size viewBox, bool drawQuietZones = true, SizingMode si /// An optional logo to be rendered on the code (either Bitmap or SVG). /// Returns the QR code graphic as an SVG string. public string GetGraphic(Size viewBox, Color darkColor, Color lightColor, bool drawQuietZones = true, SizingMode sizingMode = SizingMode.WidthHeightAttribute, SvgLogo? logo = null) - { - return GetGraphic(viewBox, ColorTranslator.ToHtml(Color.FromArgb(darkColor.ToArgb())), ColorTranslator.ToHtml(Color.FromArgb(lightColor.ToArgb())), drawQuietZones, sizingMode, logo); - } + => GetGraphic(viewBox, ColorTranslator.ToHtml(Color.FromArgb(darkColor.ToArgb())), ColorTranslator.ToHtml(Color.FromArgb(lightColor.ToArgb())), drawQuietZones, sizingMode, logo); /// /// Returns a QR code as an SVG string with custom colors (in HEX syntax), optional quiet zones, and an optional logo. @@ -220,9 +213,7 @@ public string GetGraphic(Size viewBox, string darkColorHex, string lightColorHex } private bool IsBlockedByLogo(double x, double y, ImageAttributes attr, double pixelPerModule) - { - return x + pixelPerModule >= attr.X && x <= attr.X + attr.Width && y + pixelPerModule >= attr.Y && y <= attr.Y + attr.Height; - } + => x + pixelPerModule >= attr.X && x <= attr.X + attr.Width && y + pixelPerModule >= attr.Y && y <= attr.Y + attr.Height; private ImageAttributes GetLogoAttributes(SvgLogo logo, Size viewBox) { @@ -247,13 +238,11 @@ private struct ImageAttributes public double Y; } + //Clean double values for international use/formats + //We use explicitly "G15" to avoid differences between .NET full and Core platforms + //https://stackoverflow.com/questions/64898117/tostring-has-a-different-behavior-between-net-462-and-net-core-3-1 private string CleanSvgVal(double input) - { - //Clean double values for international use/formats - //We use explicitly "G15" to avoid differences between .NET full and Core platforms - //https://stackoverflow.com/questions/64898117/tostring-has-a-different-behavior-between-net-462-and-net-core-3-1 - return input.ToString("G15", System.Globalization.CultureInfo.InvariantCulture); - } + => input.ToString("G15", System.Globalization.CultureInfo.InvariantCulture); /// /// Mode of sizing attribution on svg root node @@ -338,52 +327,35 @@ public SvgLogo(byte[] iconRasterized, int iconSizePercent = 15, bool fillLogoBac /// /// Returns the raw logo's data /// - public object GetRawLogo() - { - return _logoRaw; - } + public object GetRawLogo() => _logoRaw; /// /// Defines, if the logo shall be natively embedded. /// true=native svg embedding, false=embedding via image-tag /// - public bool IsEmbedded() - { - return _isEmbedded; - } + public bool IsEmbedded() => _isEmbedded; /// /// Returns the media type of the logo /// /// - public MediaType GetMediaType() - { - return _mediaType; - } + public MediaType GetMediaType() => _mediaType; /// /// Returns the logo as data-uri /// public string GetDataUri() - { - return $"data:{GetMimeType(_mediaType)};base64,{_logoData}"; - } + => $"data:{GetMimeType(_mediaType)};base64,{_logoData}"; /// /// Returns how much of the QR code should be covered by the logo (in percent) /// - public int GetIconSizePercent() - { - return _iconSizePercent; - } + public int GetIconSizePercent() => _iconSizePercent; /// /// Returns if the background of the logo should be cleaned (no QR modules will be rendered behind the logo) /// - public bool FillLogoBackground() - { - return _fillLogoBackground; - } + public bool FillLogoBackground() => _fillLogoBackground; /// /// Media types for SvgLogos @@ -400,15 +372,12 @@ public enum MediaType : int SVG = 1 } - private string GetMimeType(MediaType type) + private string GetMimeType(MediaType type) => type switch { - return type switch - { - MediaType.PNG => "image/png", - MediaType.SVG => "image/svg+xml", - _ => throw new ArgumentOutOfRangeException(nameof(type)), - }; - } + MediaType.PNG => "image/png", + MediaType.SVG => "image/svg+xml", + _ => throw new ArgumentOutOfRangeException(nameof(type)), + }; } } diff --git a/QRCoderConsole/Program.cs b/QRCoderConsole/Program.cs index f5a3317c..f15a7060 100644 --- a/QRCoderConsole/Program.cs +++ b/QRCoderConsole/Program.cs @@ -238,17 +238,14 @@ public QRCodeGenerator.ECCLevel GetECCLevel(string value) #if NET6_0_WINDOWS [System.Runtime.Versioning.SupportedOSPlatform("windows")] #endif - public ImageFormat GetImageFormat(string value) + public ImageFormat GetImageFormat(string value) => value.ToLower() switch { - return value.ToLower() switch - { - "jpg" => ImageFormat.Jpeg, - "jpeg" => ImageFormat.Jpeg, - "gif" => ImageFormat.Gif, - "bmp" => ImageFormat.Bmp, - "tiff" => ImageFormat.Tiff, - _ => ImageFormat.Png, - }; - } + "jpg" => ImageFormat.Jpeg, + "jpeg" => ImageFormat.Jpeg, + "gif" => ImageFormat.Gif, + "bmp" => ImageFormat.Bmp, + "tiff" => ImageFormat.Tiff, + _ => ImageFormat.Png, + }; } diff --git a/QRCoderDemo/Form1.cs b/QRCoderDemo/Form1.cs index f56e1179..305d1d28 100644 --- a/QRCoderDemo/Form1.cs +++ b/QRCoderDemo/Form1.cs @@ -114,14 +114,10 @@ private void btn_save_Click(object sender, EventArgs e) } private void textBoxQRCode_TextChanged(object sender, EventArgs e) - { - RenderQrCode(); - } + => RenderQrCode(); private void comboBoxECC_SelectedIndexChanged(object sender, EventArgs e) - { - RenderQrCode(); - } + => RenderQrCode(); private void panelPreviewPrimaryColor_Click(object sender, EventArgs e) { @@ -141,13 +137,7 @@ private void panelPreviewBackgroundColor_Click(object sender, EventArgs e) } } - private Color GetPrimaryColor() - { - return panelPreviewPrimaryColor.BackColor; - } + private Color GetPrimaryColor() => panelPreviewPrimaryColor.BackColor; - private Color GetBackgroundColor() - { - return panelPreviewBackgroundColor.BackColor; - } + private Color GetBackgroundColor() => panelPreviewBackgroundColor.BackColor; } diff --git a/QRCoderDemoUWP/App.xaml.cs b/QRCoderDemoUWP/App.xaml.cs index c503ff9f..5188504d 100644 --- a/QRCoderDemoUWP/App.xaml.cs +++ b/QRCoderDemoUWP/App.xaml.cs @@ -15,91 +15,88 @@ using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; -namespace QRCoderDemoUWP +namespace QRCoderDemoUWP; + +/// +/// Provides application-specific behavior to supplement the default Application class. +/// +internal sealed partial class App : Application { /// - /// Provides application-specific behavior to supplement the default Application class. + /// Initializes the singleton application object. This is the first line of authored code + /// executed, and as such is the logical equivalent of main() or WinMain(). /// - internal sealed partial class App : Application + public App() { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - InitializeComponent(); - Suspending += OnSuspending; - } + InitializeComponent(); + Suspending += OnSuspending; + } - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { + /// + /// Invoked when the application is launched normally by the end user. Other entry points + /// will be used such as when the application is launched to open a specific file. + /// + /// Details about the launch request and process. + protected override void OnLaunched(LaunchActivatedEventArgs e) + { #if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - DebugSettings.EnableFrameRateCounter = true; - } + if (System.Diagnostics.Debugger.IsAttached) + { + DebugSettings.EnableFrameRateCounter = true; + } #endif - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (!(Window.Current.Content is Frame rootFrame)) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } + // Do not repeat app initialization when the Window already has content, + // just ensure that the window is active + if (!(Window.Current.Content is Frame rootFrame)) + { + // Create a Frame to act as the navigation context and navigate to the first page + rootFrame = new Frame(); - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } + rootFrame.NavigationFailed += OnNavigationFailed; - if (e.PrelaunchActivated == false) + if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); + //TODO: Load state from previously suspended application } - } - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - private void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); + // Place the frame in the current Window + Window.Current.Content = rootFrame; } - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) + if (e.PrelaunchActivated == false) { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); + if (rootFrame.Content == null) + { + // When the navigation stack isn't restored navigate to the first page, + // configuring the new page by passing required information as a navigation + // parameter + rootFrame.Navigate(typeof(MainPage), e.Arguments); + } + // Ensure the current window is active + Window.Current.Activate(); } } + + /// + /// Invoked when Navigation to a certain page fails + /// + /// The Frame which failed navigation + /// Details about the navigation failure + private void OnNavigationFailed(object sender, NavigationFailedEventArgs e) + => throw new Exception("Failed to load Page " + e.SourcePageType.FullName); + + /// + /// Invoked when application execution is being suspended. Application state is saved + /// without knowing whether the application will be terminated or resumed with the contents + /// of memory still intact. + /// + /// The source of the suspend request. + /// Details about the suspend request. + private void OnSuspending(object sender, SuspendingEventArgs e) + { + var deferral = e.SuspendingOperation.GetDeferral(); + //TODO: Save application state and stop any background activity + deferral.Complete(); + } } diff --git a/QRCoderDemoUWP/MainPage.xaml.cs b/QRCoderDemoUWP/MainPage.xaml.cs index 84594443..7b2fca02 100644 --- a/QRCoderDemoUWP/MainPage.xaml.cs +++ b/QRCoderDemoUWP/MainPage.xaml.cs @@ -9,69 +9,68 @@ // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 -namespace QRCoderDemoUWP +namespace QRCoderDemoUWP; + +/// +/// An empty page that can be used on its own or navigated to within a Frame. +/// +public sealed partial class MainPage : Page { - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class MainPage : Page + public MainPage() { - public MainPage() - { - InitializeComponent(); - DataContext = this; - comboBoxECC.SelectedIndex = 0; - } + InitializeComponent(); + DataContext = this; + comboBoxECC.SelectedIndex = 0; + } #pragma warning disable IDE1006 // Naming Styles - private async void button_Click(object sender, RoutedEventArgs e) + private async void button_Click(object sender, RoutedEventArgs e) #pragma warning restore IDE1006 // Naming Styles + { + if (comboBoxECC.SelectedItem != null) { - if (comboBoxECC.SelectedItem != null) - { - //Create generator - string level = comboBoxECC.SelectedItem.ToString(); - var eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3); + //Create generator + string level = comboBoxECC.SelectedItem.ToString(); + var eccLevel = (QRCodeGenerator.ECCLevel)(level == "L" ? 0 : level == "M" ? 1 : level == "Q" ? 2 : 3); - //Create raw qr code data - var qrGenerator = new QRCodeGenerator(); - var qrCodeData = qrGenerator.CreateQrCode("The text which should be encoded.", eccLevel); + //Create raw qr code data + var qrGenerator = new QRCodeGenerator(); + var qrCodeData = qrGenerator.CreateQrCode("The text which should be encoded.", eccLevel); - //Create byte/raw bitmap qr code - var qrCodeBmp = new BitmapByteQRCode(qrCodeData); - byte[] qrCodeImageBmp = qrCodeBmp.GetGraphic(20, new byte[] { 118, 126, 152 }, new byte[] { 144, 201, 111 }); - using (var stream = new InMemoryRandomAccessStream()) + //Create byte/raw bitmap qr code + var qrCodeBmp = new BitmapByteQRCode(qrCodeData); + byte[] qrCodeImageBmp = qrCodeBmp.GetGraphic(20, new byte[] { 118, 126, 152 }, new byte[] { 144, 201, 111 }); + using (var stream = new InMemoryRandomAccessStream()) + { + using (var writer = new DataWriter(stream.GetOutputStreamAt(0))) { - using (var writer = new DataWriter(stream.GetOutputStreamAt(0))) - { - writer.WriteBytes(qrCodeImageBmp); - await writer.StoreAsync(); - } - var image = new BitmapImage(); - await image.SetSourceAsync(stream); - - imageViewerBmp.Source = image; + writer.WriteBytes(qrCodeImageBmp); + await writer.StoreAsync(); } + var image = new BitmapImage(); + await image.SetSourceAsync(stream); - //Create byte/raw png qr code - var qrCodePng = new PngByteQRCode(qrCodeData); - byte[] qrCodeImagePng = qrCodePng.GetGraphic(20, new byte[] { 144, 201, 111 }, new byte[] { 118, 126, 152 }); - using (var stream = new InMemoryRandomAccessStream()) - { - using (var writer = new DataWriter(stream.GetOutputStreamAt(0))) - { - writer.WriteBytes(qrCodeImagePng); - await writer.StoreAsync(); - } - var image = new BitmapImage(); - await image.SetSourceAsync(stream); + imageViewerBmp.Source = image; + } - imageViewerPng.Source = image; + //Create byte/raw png qr code + var qrCodePng = new PngByteQRCode(qrCodeData); + byte[] qrCodeImagePng = qrCodePng.GetGraphic(20, new byte[] { 144, 201, 111 }, new byte[] { 118, 126, 152 }); + using (var stream = new InMemoryRandomAccessStream()) + { + using (var writer = new DataWriter(stream.GetOutputStreamAt(0))) + { + writer.WriteBytes(qrCodeImagePng); + await writer.StoreAsync(); } + var image = new BitmapImage(); + await image.SetSourceAsync(stream); + + imageViewerPng.Source = image; } } - - public List EccModes => Enum.GetValues(typeof(QRCodeGenerator.ECCLevel)).Cast().Select(x => x.ToString()).ToList(); } + + public List EccModes => Enum.GetValues(typeof(QRCodeGenerator.ECCLevel)).Cast().Select(x => x.ToString()).ToList(); }