4 Commits

Author SHA1 Message Date
aziascreations 60a7cb0f6b Added .NET Framework 4 target for application
Update ErrorCodes.cs, NibblePoker.Application.ListComPort.csproj, and 2 more files...
2024-05-24 16:49:02 +02:00
aziascreations 6e4462c8fa Added .NET Framework 4 target for "ComPortHelper" library
Update ComPortHelper.cs, ComPortInfo.cs, and 2 more files...
2024-05-24 16:35:15 +02:00
aziascreations 20052c3fb4 Added .net 7 and .net 8 targets, Fixed bug in args parsing, Removed debug builds & drone config, Updated dependencies
Update .drone.yml, .gitignore, and 4 more files...
2024-05-24 00:08:50 +02:00
aziascreations 2bf8401f51 Switching to "CC0-1.0" license
Update LICENSE and readme.md
2024-05-23 23:53:19 +02:00
12 changed files with 484 additions and 334 deletions
-18
View File
@@ -1,18 +0,0 @@
# Documentation:
# * https://docs.drone.io/quickstart/docker/
# * https://docs.drone.io/pipeline/docker/examples/languages/csharp/
# * https://discourse.drone.io/t/builds-are-stuck-in-pending-status/4437
kind: pipeline
type: docker
name: default
platform:
os: linux
arch: arm64
steps:
- name: test
image: mcr.microsoft.com/dotnet/sdk:6.0-alpine
commands:
- dotnet build "./NibblePoker.Application.ListComPort/NibblePoker.Application.ListComPort.csproj"
+3
View File
@@ -1,6 +1,8 @@
# IDEs
.idea/
.vs/
# Build Artifacts
Builds/any/
Builds/arm*/
Builds/x*/
@@ -25,4 +27,5 @@ Packages/
*.wixobj
*.wixpdb
# Misc
notes.txt
-4
View File
@@ -10,12 +10,8 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2E9CEFC2-66A8-4A03-84FB-C28F752F522C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E9CEFC2-66A8-4A03-84FB-C28F752F522C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E9CEFC2-66A8-4A03-84FB-C28F752F522C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E9CEFC2-66A8-4A03-84FB-C28F752F522C}.Release|Any CPU.Build.0 = Release|Any CPU
{0E6E464E-8497-4752-8281-24A64E5E8A9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0E6E464E-8497-4752-8281-24A64E5E8A9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0E6E464E-8497-4752-8281-24A64E5E8A9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0E6E464E-8497-4752-8281-24A64E5E8A9D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
+118 -4
View File
@@ -1,7 +1,121 @@
Copyright 2022 BOZET Herwin
Creative Commons Legal Code
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
CC0 1.0 Universal
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
@@ -1,20 +1,20 @@
namespace NibblePoker.Application.ListComPort;
namespace NibblePoker.Application.ListComPort {
public static class ErrorCodes {
public const int NoError = 0;
public static class ErrorCodes {
public const int NoError = 0;
/* Fatal errors (1-9) */
// Not needed in C#
/* Internal argument parser errors (10-19) */
public const int ArgumentParsingFailure = 10;
// ArgumentDefinitionFailure = 11 => Cannot happen due to the way options are declared. (Caught in development)
// ArgumentInitFailure = 12 => Cannot happen with "NibblePoker.Library.Arguments".
/* External argument errors (20-29) */
public const int NoPaddingValue = 20;
/* Application & System errors (30-39) */
// NoFriendlyNames = 30 => Causes problems with broad-range exit code checks.
public const int NoComPorts = 31;
}
/* Fatal errors (1-9) */
// Not needed in C#
/* Internal argument parser errors (10-19) */
public const int ArgumentParsingFailure = 10;
// ArgumentDefinitionFailure = 11 => Cannot happen due to the way options are declared. (Caught in development)
// ArgumentInitFailure = 12 => Cannot happen with "NibblePoker.Library.Arguments".
/* External argument errors (20-29) */
public const int NoPaddingValue = 20;
/* Application & System errors (30-39) */
// NoFriendlyNames = 30 => Causes problems with broad-range exit code checks.
public const int NoComPorts = 31;
}
}
@@ -2,14 +2,16 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TargetFrameworks>net40;net6.0-windows;net7.0-windows;net8.0-windows</TargetFrameworks>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
<RootNamespace>NibblePoker.Application.ListComPort</RootNamespace>
<AssemblyName>NibblePoker.Application.ListComPort</AssemblyName>
<AssemblyVersion>3.0.0</AssemblyVersion>
<FileVersion>3.0.0</FileVersion>
<Version>3.0.0</Version>
<AssemblyVersion>4.0.0</AssemblyVersion>
<FileVersion>4.0.0</FileVersion>
<Version>4.0.0</Version>
<NeutralLanguage>en-001</NeutralLanguage>
<IsPackable>false</IsPackable>
<Authors>Herwin Bozet (@NibblePoker)</Authors>
@@ -21,7 +23,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="NibblePoker.Library.Arguments" Version="1.1.0" />
<PackageReference Include="NibblePoker.Library.Arguments" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
+233 -189
View File
@@ -4,204 +4,248 @@ using System.Linq;
using NibblePoker.Library.Arguments;
using NibblePoker.Library.ComPortWatcher;
namespace NibblePoker.Application.ListComPort;
namespace NibblePoker.Application.ListComPort {
internal static class Program {
private const string Version = "4.0.0";
internal static class Program {
private const string Version = "3.0.0";
private static readonly Verb RootVerb = new Verb("");
private static readonly Option OptionShowAll = new('a', "show-all", "Display the complete port's name (Equal to '-dfn')");
private static readonly Option OptionShowDevice = new('d', "show-device", "Displays the port's device name");
private static readonly Option OptionDivider = new('D', "divider", "Uses the given string or char as a separator (Can be an empty string !)", OptionFlags.HasValue);
private static readonly Option OptionShowFriendly = new('f', "show-friendly", "Displays the port's friendly name");
private static readonly Option OptionHelp = new('h', "help", "Display the help text", OptionFlags.StopsParsing);
private static readonly Option OptionHelpShort = new('H', "short-help", "Display the short help text", OptionFlags.StopsParsing);
private static readonly Option OptionShowNameRaw = new('n', "show-name-raw", "Displays the port's raw name (See remarks section)");
private static readonly Option OptionNoPretty = new('P', "no-pretty", "Disables the pretty printing format (Equal to -D \" \"");
private static readonly Option OptionSort = new('s', "sort", "Sorts the port based on their raw names in an ascending order");
private static readonly Option OptionSortReverse = new('S', "sort-reverse", "Sorts the port based on their raw names in a descending order");
private static readonly Option OptionTabPadding = new('t', "tab-padding", "Use tabs for padding between the types of names (Overrides '-D')");
private static readonly Option OptionVersion = new('v', "version", "Shows the utility's version number and other info");
private static readonly Option OptionVersionOnly = new('V', "version-only", "Shows the utility's version number only (Overrides '-v')");
private static bool _shouldPrintRawNames = true;
private static bool _shouldPrintDeviceNames = false;
private static bool _shouldPrintFriendlyNames = false;
private static string _paddingText = "";
// ReSharper disable once InconsistentNaming
private static readonly Verb RootVerb = new Verb(null);
private static SortingOrder _sortingOrder = SortingOrder.None;
private static int _exitCode = ErrorCodes.NoError;
/// <summary>
/// Checks if the program is the only owner of its console.
/// This check is used to detect if the program was run from the exe/lnk or via a console.
/// </summary>
/// <returns><c>True</c> if the process is the console's sole owner, <c>False</c> otherwise</returns>
private static bool IsProgramRunDirectly() {
return GetConsoleProcessList(new int[2], 2) <= 1;
}
private static int Main(string[] args) {
try {
ArgumentsParser.ParseArguments(RootVerb.RegisterOption(OptionShowAll).RegisterOption(OptionShowDevice)
.RegisterOption(OptionDivider).RegisterOption(OptionShowFriendly).RegisterOption(OptionHelp)
.RegisterOption(OptionShowNameRaw).RegisterOption(OptionNoPretty).RegisterOption(OptionSort)
.RegisterOption(OptionSortReverse).RegisterOption(OptionTabPadding).RegisterOption(OptionVersion)
.RegisterOption(OptionVersionOnly), args);
} catch(ArgumentException) {
Console.Error.Write("Failed to parse the launch arguments, default options will be used.");
_exitCode = ErrorCodes.ArgumentParsingFailure;
RootVerb.Clear();
}
private static readonly Option OptionShowAll = new Option('a', "show-all",
"Display the complete port's name (Equal to '-dfn')");
private static readonly Option OptionShowDevice = new Option('d', "show-device",
"Displays the port's device name");
private static readonly Option OptionShowFriendly = new Option('f', "show-friendly",
"Displays the port's friendly name");
private static readonly Option OptionShowNameRaw = new Option('n', "show-name-raw",
"Displays the port's raw name (See remarks section)");
if(OptionHelp.WasUsed() || OptionHelpShort.WasUsed()) {
Console.WriteLine(HelpText.GetFullHelpText(RootVerb, "lscom.exe", (uint)Console.BufferWidth - 1, 1, 2, false));
if(OptionHelp.WasUsed()) {
Console.WriteLine("\nRemarks:");
Console.WriteLine(" * If '-d' or '-f' is used, the raw name will not be shown unless '-n' is used.");
Console.WriteLine(" * If '-D', '-t' or '-p' are used, the special separator between the raw and friendly name and the square brackets are not shown.");
Console.WriteLine(" * If the program is raw without going through a console, the options '-n' and '-f' will be used.");
Console.WriteLine(" * By default, the ports are sorted in the order they are provided by the registry, which is often chronological.");
Console.WriteLine(" * The 'raw name' refers to a port name. (e.g.: COM1, COM2, ...)");
Console.WriteLine(" * The 'device name' refers to a port device path. (e.g.: \\Device\\Serial1, ...)");
Console.WriteLine(" * The 'friendly name' refers to a port name as seen in the device manager. (e.g.: Communications Port, USB-SERIAL CH340, ...)");
Console.WriteLine(" * Any result returned with an error code between 1-9 and 30-39 should be considered as invalid.");
Console.WriteLine(" * Any result returned with another error code is valid but probably not formatted properly.");
private static readonly Option OptionDivider = new Option('D', "divider",
"Uses the given string or char as a separator (Can be an empty string !)", OptionFlags.HasValue);
private static readonly Option OptionTabPadding = new Option('t', "tab-padding",
"Use tabs for padding between the types of names (Overrides '-D')");
private static readonly Option OptionNoPretty = new Option('P', "no-pretty",
"Disables the pretty printing format (Equal to -D \" \"");
private static readonly Option OptionSort = new Option('s', "sort",
"Sorts the port based on their raw names in an ascending order");
private static readonly Option OptionSortReverse = new Option('S', "sort-reverse",
"Sorts the port based on their raw names in a descending order");
private static readonly Option OptionHelp = new Option('h', "help",
"Display the help text", OptionFlags.StopsParsing);
private static readonly Option OptionHelpShort = new Option('H', "short-help",
"Display the short help text", OptionFlags.StopsParsing);
private static readonly Option OptionVersion = new Option('v', "version",
"Shows the utility's version number and other info");
private static readonly Option OptionVersionOnly = new Option('V', "version-only",
"Shows the utility's version number only (Overrides '-v')");
// ReSharper disable RedundantDefaultMemberInitializer
private static bool _shouldPrintRawNames = true;
private static bool _shouldPrintDeviceNames = false;
private static bool _shouldPrintFriendlyNames = false;
// ReSharper enable RedundantDefaultMemberInitializer
private static string _paddingText = "";
private static SortingOrder _sortingOrder = SortingOrder.None;
private static int _exitCode = ErrorCodes.NoError;
/// <summary>
/// Checks if the program is the only owner of its console.
/// This check is used to detect if the program was run from the exe/lnk or via a console.
/// </summary>
/// <returns><c>True</c> if the process is the console's sole owner, <c>False</c> otherwise</returns>
private static bool IsProgramRunDirectly() {
return GetConsoleProcessList(new int[2], 2) <= 1;
}
private static int Main(string[] args) {
// Preparing & parsing launch arguments
try {
ArgumentsParser.ParseArguments(RootVerb.RegisterOption(OptionShowAll).RegisterOption(OptionShowDevice)
.RegisterOption(OptionDivider).RegisterOption(OptionShowFriendly).RegisterOption(OptionHelp)
.RegisterOption(OptionShowNameRaw).RegisterOption(OptionNoPretty).RegisterOption(OptionSort)
.RegisterOption(OptionSortReverse).RegisterOption(OptionTabPadding).RegisterOption(OptionVersion)
.RegisterOption(OptionVersionOnly), args);
} catch(Exceptions.ArgumentsException) {
Console.Error.WriteLine("Failed to parse the launch arguments, default options will be used.");
_exitCode = ErrorCodes.ArgumentParsingFailure;
RootVerb.Clear();
}
return ErrorCodes.NoError;
}
if(OptionVersionOnly.WasUsed()) {
Console.WriteLine(Version);
return ErrorCodes.NoError;
}
if(OptionVersion.WasUsed()) {
Console.WriteLine("NibblePoker.Application.ListComPort (lscom) v" + Version);
Console.WriteLine("");
Console.WriteLine("Dependencies:");
Console.WriteLine("├─> NibblePoker.Library.Arguments v1.1.0");
Console.WriteLine("├─> NibblePoker.Library.ComPortHelpers v" + Version);
Console.WriteLine("└─> NibblePoker.Library.RegistryHelpers v0.0.1");
Console.WriteLine("");
Console.WriteLine("GitHub repositories:");
Console.WriteLine("├─> https://github.com/aziascreations/DotNet-Arguments");
Console.WriteLine("├─> https://github.com/aziascreations/DotNet-ListComPort");
Console.WriteLine("└─> https://github.com/aziascreations/DotNet-RegistryHelpers");
Console.WriteLine("");
Console.WriteLine("This software and all its libraries are licensed under the MIT license.");
return ErrorCodes.NoError;
}
if(OptionShowDevice.WasUsed()) {
_shouldPrintRawNames = false;
_shouldPrintDeviceNames = true;
}
if(OptionShowFriendly.WasUsed() || IsProgramRunDirectly()) {
_shouldPrintRawNames = false;
_shouldPrintFriendlyNames = true;
}
if(OptionShowNameRaw.WasUsed() || IsProgramRunDirectly()) {
_shouldPrintRawNames = true;
}
if(OptionShowAll.WasUsed()) {
_shouldPrintRawNames = true;
_shouldPrintFriendlyNames = true;
_shouldPrintDeviceNames = true;
}
if(OptionSort.WasUsed()) {
_sortingOrder = SortingOrder.Ascending;
}
if(OptionSortReverse.WasUsed()) {
_sortingOrder = SortingOrder.Descending;
}
if(OptionNoPretty.WasUsed()) {
_paddingText = " ";
}
if(OptionDivider.WasUsed()) {
_paddingText = OptionDivider.Arguments[0];
}
if(OptionTabPadding.WasUsed()) {
_paddingText = "\t";
}
// Application's code
string rawToFriendlySeparator = " - ";
bool addDeviceBrackets = true;
if(string.IsNullOrEmpty(_paddingText)) {
_paddingText = " ";
} else {
rawToFriendlySeparator = _paddingText;
addDeviceBrackets = false;
}
if(!_shouldPrintRawNames && !_shouldPrintFriendlyNames && _shouldPrintDeviceNames) {
addDeviceBrackets = false;
}
List<ComPortInfo> comPortsInfo = ComPortHelper.GetComList(_shouldPrintFriendlyNames);
if(comPortsInfo.Count > 0) {
comPortsInfo = _sortingOrder switch {
SortingOrder.Ascending => comPortsInfo.OrderBy(o => o.RawName).ToList(),
SortingOrder.Descending => comPortsInfo.OrderByDescending(o => o.RawName).ToList(),
_ => comPortsInfo
};
foreach(ComPortInfo comPortInfo in comPortsInfo) {
if(_shouldPrintRawNames) {
Console.Write(comPortInfo.RawName);
// Processing exiting options
if(OptionHelp.WasUsed() || OptionHelpShort.WasUsed()) {
Console.WriteLine(HelpText.GetFullHelpText(
RootVerb, "lscom.exe",
(uint)Console.BufferWidth - 1, 1, 2, false));
if(OptionHelp.WasUsed()) {
Console.WriteLine("\nRemarks:");
Console.WriteLine(
" * If '-d' or '-f' is used, the raw name will not be shown unless '-n' is used.");
Console.WriteLine(
" * If '-D', '-t' or '-p' are used, the special separator between the raw and friendly name and the square brackets are not shown.");
Console.WriteLine(
" * If the program is raw without going through a console, the options '-n' and '-f' will be used.");
Console.WriteLine(
" * By default, the ports are sorted in the order they are provided by the registry, which is often chronological.");
Console.WriteLine(" * The 'raw name' refers to a port name. (e.g.: COM1, COM2, ...)");
Console.WriteLine(
" * The 'device name' refers to a port device path. (e.g.: \\Device\\Serial1, ...)");
Console.WriteLine(
" * The 'friendly name' refers to a port name as seen in the device manager. (e.g.: Communications Port, USB-SERIAL CH340, ...)");
Console.WriteLine(
" * Any result returned with an error code between 1-9 and 30-39 should be considered as invalid.");
Console.WriteLine(
" * Any result returned with another error code is valid but probably not formatted properly.");
}
return ErrorCodes.NoError;
}
if(OptionVersionOnly.WasUsed()) {
Console.WriteLine(Version);
return ErrorCodes.NoError;
}
if(OptionVersion.WasUsed()) {
Console.WriteLine("NibblePoker.Application.ListComPort (lscom) v" + Version);
Console.WriteLine("");
Console.WriteLine("Dependencies:");
Console.WriteLine("├─> NibblePoker.Library.Arguments v2.0.0");
Console.WriteLine("├─> NibblePoker.Library.ComPortHelpers v" + Version);
Console.WriteLine("└─> NibblePoker.Library.RegistryHelpers v1.0.0");
Console.WriteLine("");
Console.WriteLine("GitHub repositories:");
Console.WriteLine("├─> https://github.com/aziascreations/DotNet-Arguments");
Console.WriteLine("├─> https://github.com/aziascreations/DotNet-ListComPort");
Console.WriteLine("└─> https://github.com/aziascreations/DotNet-RegistryHelpers");
Console.WriteLine("");
Console.WriteLine(
"This software and all its libraries are released in the public domain under the CC0-1.0 license.");
return ErrorCodes.NoError;
}
// Processing parameter options
if(OptionShowDevice.WasUsed()) {
_shouldPrintRawNames = false;
_shouldPrintDeviceNames = true;
}
if(OptionShowFriendly.WasUsed() || IsProgramRunDirectly()) {
_shouldPrintRawNames = false;
_shouldPrintFriendlyNames = true;
}
if(OptionShowNameRaw.WasUsed() || IsProgramRunDirectly()) {
_shouldPrintRawNames = true;
}
if(OptionShowAll.WasUsed()) {
_shouldPrintRawNames = true;
_shouldPrintFriendlyNames = true;
_shouldPrintDeviceNames = true;
}
if(OptionSort.WasUsed()) {
_sortingOrder = SortingOrder.Ascending;
}
if(OptionSortReverse.WasUsed()) {
_sortingOrder = SortingOrder.Descending;
}
if(OptionNoPretty.WasUsed()) {
_paddingText = " ";
}
if(OptionDivider.WasUsed()) {
_paddingText = OptionDivider.Arguments[0];
}
if(OptionTabPadding.WasUsed()) {
_paddingText = "\t";
}
// Application's code
string rawToFriendlySeparator = " - ";
bool addDeviceBrackets = true;
if(string.IsNullOrEmpty(_paddingText)) {
_paddingText = " ";
} else {
rawToFriendlySeparator = _paddingText;
addDeviceBrackets = false;
}
if(!_shouldPrintRawNames && !_shouldPrintFriendlyNames && _shouldPrintDeviceNames) {
addDeviceBrackets = false;
}
List<ComPortInfo> comPortsInfo = ComPortHelper.GetComList(_shouldPrintFriendlyNames);
if(comPortsInfo.Count > 0) {
//comPortsInfo = _sortingOrder switch {
// SortingOrder.Ascending => comPortsInfo.OrderBy(o => o.RawName).ToList(),
// SortingOrder.Descending => comPortsInfo.OrderByDescending(o => o.RawName).ToList(),
// _ => comPortsInfo
//};
switch(_sortingOrder) {
case SortingOrder.Ascending:
comPortsInfo = comPortsInfo.OrderBy(o => o.RawName).ToList();
break;
case SortingOrder.Descending:
comPortsInfo = comPortsInfo.OrderByDescending(o => o.RawName).ToList();
break;
case SortingOrder.None:
default:
break;
}
foreach(ComPortInfo comPortInfo in comPortsInfo) {
if(_shouldPrintRawNames) {
Console.Write(comPortInfo.RawName);
if(_shouldPrintFriendlyNames) {
Console.Write(rawToFriendlySeparator);
}
}
if(_shouldPrintFriendlyNames) {
Console.Write(rawToFriendlySeparator);
Console.Write(comPortInfo.FriendlyName);
}
if((_shouldPrintRawNames || _shouldPrintFriendlyNames) && _shouldPrintDeviceNames) {
Console.Write(_paddingText);
}
if(_shouldPrintDeviceNames) {
Console.Write((addDeviceBrackets ? "[" : "") + comPortInfo.DeviceName +
(addDeviceBrackets ? "]" : ""));
}
Console.WriteLine();
}
if(_shouldPrintFriendlyNames) {
Console.Write(comPortInfo.FriendlyName);
}
if((_shouldPrintRawNames || _shouldPrintFriendlyNames) && _shouldPrintDeviceNames) {
Console.Write(_paddingText);
}
if(_shouldPrintDeviceNames) {
Console.Write((addDeviceBrackets ? "[" : "") + comPortInfo.DeviceName + (addDeviceBrackets ? "]" : ""));
}
Console.WriteLine();
} else {
Console.Error.Write("No COM port could be found.");
_exitCode = ErrorCodes.NoComPorts;
}
} else {
Console.Error.Write("No COM port could be found.");
_exitCode = ErrorCodes.NoComPorts;
// Allows the program to be run from a shortcut without closing the console instantly.
if(IsProgramRunDirectly()) {
Console.Write("\nPress any key to continue...");
Console.ReadKey();
}
return _exitCode;
}
// Allows the program to be ran from a shortcut without closing the console instantly.
if(IsProgramRunDirectly()) {
Console.Write("\nPress any key to continue...");
Console.ReadKey();
}
return _exitCode;
// Imports "GetConsoleProcessList(...)" in order to know if the program was run via a shortcut or a CLI prompt.
// See: https://learn.microsoft.com/en-us/windows/console/getconsoleprocesslist
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern int GetConsoleProcessList(int[] buffer, int size);
}
// Imports "GetConsoleProcessList(...)" in order to know if the program was ran via a shortcut or CLI.
// See: https://learn.microsoft.com/en-us/windows/console/getconsoleprocesslist
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern int GetConsoleProcessList(int[] buffer, int size);
}
@@ -1,73 +1,81 @@
using Microsoft.Win32;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Win32;
using static NibblePoker.Library.RegistryHelpers.RegistryHelpers;
namespace NibblePoker.Library.ComPortWatcher;
namespace NibblePoker.Library.ComPortWatcher {
public static class ComPortHelper {
private const string RegistryKeySerial = "HARDWARE\\DEVICEMAP\\SERIALCOMM";
private const string RegistryKeyDeviceEnum = "SYSTEM\\ControlSet001\\Enum";
public static class ComPortHelper {
private const string RegistryKeySerial = "HARDWARE\\DEVICEMAP\\SERIALCOMM";
private const string RegistryKeyDeviceEnum = "SYSTEM\\ControlSet001\\Enum";
private static readonly string[] IgnoredRegistryDeviceEnums = {
"ACPI", "ACPI_HAL", "HDAUDIO", "SCSI", "STORAGE", "SW", "SWD", "UEFI"
};
private const string RegistryNameFriendlyName = "FriendlyName";
private static void AddFriendlyNamesToPortsInfo(List<ComPortInfo> comPortsInfo) {
List<string> subKeys = GetSubKeys(Registry.LocalMachine, RegistryKeyDeviceEnum);
List<string> intermediateSubKeys = new List<string>();
List<string> finalSubKeys = new List<string>();
List<string> friendlyNames = new List<string>();
foreach(var subKey in subKeys.Where(subKey => !IgnoredRegistryDeviceEnums.Contains(subKey))) {
intermediateSubKeys.AddRange(GetSubKeys(
Registry.LocalMachine,
RegistryKeyDeviceEnum + "\\" + subKey,
true));
}
subKeys.Clear();
foreach(string subSubKey in intermediateSubKeys) {
finalSubKeys.AddRange(GetSubKeys(
Registry.LocalMachine,
subSubKey,
true));
}
intermediateSubKeys.Clear();
foreach(string finalSubKey in finalSubKeys) {
Dictionary<string, string> mappedKeyValues = GetMappedKeyNameStringValue(Registry.LocalMachine, finalSubKey);
if(mappedKeyValues.ContainsKey(RegistryNameFriendlyName)) {
friendlyNames.Add(mappedKeyValues[RegistryNameFriendlyName]);
private static readonly string[] IgnoredRegistryDeviceEnums = {
"ACPI", "ACPI_HAL", "HDAUDIO", "SCSI", "STORAGE", "SW", "SWD", "UEFI"
};
private const string RegistryNameFriendlyName = "FriendlyName";
private static void AddFriendlyNamesToPortsInfo(List<ComPortInfo> comPortsInfo) {
List<string> subKeys = GetSubKeys(Registry.LocalMachine, RegistryKeyDeviceEnum);
List<string> intermediateSubKeys = new List<string>();
List<string> finalSubKeys = new List<string>();
List<string> friendlyNames = new List<string>();
foreach(var subKey in subKeys.Where(subKey => !IgnoredRegistryDeviceEnums.Contains(subKey))) {
intermediateSubKeys.AddRange(GetSubKeys(
Registry.LocalMachine,
RegistryKeyDeviceEnum + "\\" + subKey,
true));
}
}
finalSubKeys.Clear();
foreach(ComPortInfo comPortInfo in comPortsInfo) {
foreach(string friendlyName in friendlyNames) {
if(!friendlyName.Contains("(" + comPortInfo.RawName + ")")) {
continue;
subKeys.Clear();
foreach(string subSubKey in intermediateSubKeys) {
finalSubKeys.AddRange(GetSubKeys(
Registry.LocalMachine,
subSubKey,
true));
}
intermediateSubKeys.Clear();
foreach(string finalSubKey in finalSubKeys) {
Dictionary<string, string> mappedKeyValues =
GetMappedKeyNameStringValue(Registry.LocalMachine, finalSubKey);
if(mappedKeyValues.ContainsKey(RegistryNameFriendlyName)) {
friendlyNames.Add(mappedKeyValues[RegistryNameFriendlyName]);
}
comPortInfo.FriendlyName = friendlyName;
break;
}
}
friendlyNames.Clear();
}
public static List<ComPortInfo> GetComList(bool addFriendlyNames = false) {
List<ComPortInfo> portsInfo = new List<ComPortInfo>();
foreach(KeyValuePair<string, string> rawPortInfo in GetMappedKeyNameStringValue(Registry.LocalMachine, RegistryKeySerial)) {
portsInfo.Add(new ComPortInfo(rawPortInfo.Value, rawPortInfo.Key));
finalSubKeys.Clear();
foreach(ComPortInfo comPortInfo in comPortsInfo) {
foreach(string friendlyName in friendlyNames) {
if(!friendlyName.Contains("(" + comPortInfo.RawName + ")")) {
continue;
}
comPortInfo.FriendlyName = friendlyName;
break;
}
}
friendlyNames.Clear();
}
if(addFriendlyNames && portsInfo.Count > 0) {
AddFriendlyNamesToPortsInfo(portsInfo);
public static List<ComPortInfo> GetComList(bool addFriendlyNames = false) {
List<ComPortInfo> portsInfo = new List<ComPortInfo>();
foreach(KeyValuePair<string, string> rawPortInfo in GetMappedKeyNameStringValue(Registry.LocalMachine,
RegistryKeySerial)) {
portsInfo.Add(new ComPortInfo(rawPortInfo.Value, rawPortInfo.Key));
}
if(addFriendlyNames && portsInfo.Count > 0) {
AddFriendlyNamesToPortsInfo(portsInfo);
}
return portsInfo;
}
return portsInfo;
}
}
@@ -1,18 +1,18 @@
namespace NibblePoker.Library.ComPortWatcher;
namespace NibblePoker.Library.ComPortWatcher {
public class ComPortInfo {
public string RawName;
public string DeviceName;
public string FriendlyName;
public class ComPortInfo {
public string RawName;
public string DeviceName;
public string FriendlyName;
public ComPortInfo(string rawName, string deviceName, string friendlyName = "") {
RawName = rawName;
DeviceName = deviceName;
if(string.IsNullOrEmpty(friendlyName)) {
FriendlyName = "No friendly name found (" + rawName + ")";
} else {
FriendlyName = friendlyName;
public ComPortInfo(string rawName, string deviceName, string friendlyName = "") {
RawName = rawName;
DeviceName = deviceName;
if(string.IsNullOrEmpty(friendlyName)) {
FriendlyName = "No friendly name found (" + rawName + ")";
} else {
FriendlyName = friendlyName;
}
}
}
}
}
@@ -1,15 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TargetFrameworks>net40;net6.0-windows;net7.0-windows;net8.0-windows</TargetFrameworks>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
<RootNamespace>NibblePoker.Library.ComPortWatcher</RootNamespace>
<AssemblyName>NibblePoker.Library.ComPortHelpers</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NibblePoker.Library.RegistryHelpers" Version="0.0.1" />
<PackageReference Include="NibblePoker.Library.RegistryHelpers" Version="1.0.0" />
</ItemGroup>
</Project>
@@ -1,7 +1,7 @@
namespace NibblePoker.Library.ComPortWatcher;
public enum SortingOrder {
Descending = -1,
None = 0,
Ascending = 1,
namespace NibblePoker.Library.ComPortWatcher {
public enum SortingOrder {
Descending = -1,
None = 0,
Ascending = 1,
}
}
+5 -6
View File
@@ -102,12 +102,11 @@ Finally, you should be able to find the executables in the "[Builds](Builds/)" f
and the distributable packages in the "[Packages](Packages/)" folder.
## Licenses
## License
The code in this repository is licensed under [CC0 1.0 Universal (CC0 1.0) (Public Domain)](LICENSE).
### Repository
This project and all the libraries it uses are licensed under the [MIT](LICENSE) license.
### Builds
Some of the final binaries are covered by additional licenses, they are present in the "[NibblePoker.Packaging.ListComPort/Licenses](NibblePoker.Packaging.ListComPort/Licenses)" folder and are automatically packaged with the appropriate builds during the packaging process.
Some of the final binaries are covered by additional licenses, they are present in the
"[NibblePoker.Packaging.ListComPort/Licenses](NibblePoker.Packaging.ListComPort/Licenses)"
folder and are automatically packaged with the appropriate builds during the packaging process.
[TODO: Add details]