├── .gitignore ├── .idea └── .idea.MaxRunSoftware.Utilities │ └── .idea │ ├── .gitignore │ ├── .name │ ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml │ ├── encodings.xml │ ├── indexLayout.xml │ ├── inspectionProfiles │ └── Project_Default.xml │ └── vcs.xml ├── LICENSE ├── MaxRunSoftware.Utilities.Console ├── Args.cs ├── Command.cs ├── CommandException.cs ├── CommandHelpBuilder.cs ├── Commands │ ├── ActiveDirectoryAddGroup.cs │ ├── ActiveDirectoryAddOU.cs │ ├── ActiveDirectoryAddUser.cs │ ├── ActiveDirectoryAddUserToGroup.cs │ ├── ActiveDirectoryBase.cs │ ├── ActiveDirectoryChangePassword.cs │ ├── ActiveDirectoryDisableUser.cs │ ├── ActiveDirectoryDisableUsers.cs │ ├── ActiveDirectoryEnableUser.cs │ ├── ActiveDirectoryList.cs │ ├── ActiveDirectoryListBase.cs │ ├── ActiveDirectoryListComputers.cs │ ├── ActiveDirectoryListGroups.cs │ ├── ActiveDirectoryListObjectDetails.cs │ ├── ActiveDirectoryListObjects.cs │ ├── ActiveDirectoryListUsers.cs │ ├── ActiveDirectoryListUsersOfGroup.cs │ ├── ActiveDirectoryMoveGroup.cs │ ├── ActiveDirectoryMoveUser.cs │ ├── ActiveDirectoryRemoveGroup.cs │ ├── ActiveDirectoryRemoveOU.cs │ ├── ActiveDirectoryRemoveUser.cs │ ├── ActiveDirectoryRemoveUserFromGroup.cs │ ├── Colors.cs │ ├── Convert.cs │ ├── DirectoryFlatten.cs │ ├── DirectoryList.cs │ ├── DirectoryRemoveEmpty.cs │ ├── DirectorySize.cs │ ├── Email.cs │ ├── EncodePassword.cs │ ├── FileAppend.cs │ ├── FileChecksum.cs │ ├── FileDecrypt.cs │ ├── FileEncrypt.cs │ ├── FileRemoveMacMeta.cs │ ├── FileRemoveOlderThen.cs │ ├── FileReplaceString.cs │ ├── FileSplit.cs │ ├── FtpBase.cs │ ├── FtpDelete.cs │ ├── FtpGet.cs │ ├── FtpList.cs │ ├── FtpMGet.cs │ ├── FtpMPut.cs │ ├── FtpPut.cs │ ├── GenerateKeyPair.cs │ ├── GenerateRandomFile.cs │ ├── GoogleSheetsAddRow.cs │ ├── GoogleSheetsBase.cs │ ├── GoogleSheetsClear.cs │ ├── GoogleSheetsFormatCells.cs │ ├── GoogleSheetsLoad.cs │ ├── GoogleSheetsQuery.cs │ ├── Guid.cs │ ├── Jsas.cs │ ├── ShowProperties.cs │ ├── Sql.cs │ ├── SqlBase.cs │ ├── SqlBinary.cs │ ├── SqlDownload.cs │ ├── SqlLoad.cs │ ├── SqlQueryBase.cs │ ├── Ssh.cs │ ├── SystemInfo.cs │ ├── Table.cs │ ├── TableBase.cs │ ├── TableFixedWidth.cs │ ├── TableHtml.cs │ ├── TableJson.cs │ ├── TableTranspose.cs │ ├── TableXml.cs │ ├── Time.cs │ ├── VMwareBase.cs │ ├── VMwareList.cs │ ├── VMwareListJSON.cs │ ├── VMwareQuery.cs │ ├── VMwareVM.cs │ ├── Versions.cs │ ├── WGet.cs │ ├── WebBrowser.cs │ ├── WebServer.cs │ ├── WebServerBase.cs │ ├── WebServerBucketStore.cs │ ├── WebServerUtility.cs │ ├── WebServerUtilityBase.cs │ ├── WebServerUtilityEncryptFile.cs │ ├── WebServerUtilityGenerateKeyPair.cs │ ├── WebServerUtilityGenerateRandom.cs │ ├── WebServerUtilityGenerateRandomFile.cs │ ├── WebServerUtilitySql.cs │ ├── WindowsTaskSchedulerAdd.cs │ ├── WindowsTaskSchedulerBase.cs │ ├── WindowsTaskSchedulerBatchSync.cs │ ├── WindowsTaskSchedulerList.cs │ ├── WindowsTaskSchedulerRemove.cs │ ├── Xslt.cs │ ├── Zip.cs │ └── ZipMany.cs ├── ConfigFile.cs ├── Encoding.cs ├── Extensions.cs ├── ICommand.cs ├── Icon.ico ├── MaxRunSoftware.Utilities.Console.csproj ├── Program.cs └── Version.cs ├── MaxRunSoftware.Utilities.External ├── ActiveDirectory │ ├── ActiveDirectory.cs │ ├── ActiveDirectoryCore.cs │ ├── ActiveDirectoryExtensions.cs │ ├── ActiveDirectoryGroupType.cs │ ├── ActiveDirectoryObject.cs │ ├── ActiveDirectoryObjectCache.cs │ └── ActiveDirectoryUserAccountControl.cs ├── Encryption.cs ├── Ftp │ ├── FtpClientBase.cs │ ├── FtpClientFile.cs │ ├── FtpClientFileType.cs │ ├── FtpClientFtp.cs │ ├── FtpClientFtpSEncryptionMode.cs │ ├── FtpClientSFtp.cs │ └── IFtpClient.cs ├── GitHub.cs ├── GoogleSheets.cs ├── Ldap │ ├── Ldap.cs │ ├── LdapEntryAttributeCollection.cs │ ├── LdapEntryAttributeValue.cs │ ├── LdapExtensions.cs │ └── LdapQueryConfig.cs ├── Logging.cs ├── MaxRunSoftware.Utilities.External.csproj ├── MaxRunSoftware.Utilities.External.csproj.DotSettings ├── Ssh.cs ├── VMware │ ├── VMwareClient.cs │ ├── VMwareDatacenter.cs │ ├── VMwareDatastore.cs │ ├── VMwareExtensions.cs │ ├── VMwareFolder.cs │ ├── VMwareHost.cs │ ├── VMwareNetwork.cs │ ├── VMwareObject.cs │ ├── VMwareResourcePool.cs │ ├── VMwareStoragePolicy.cs │ ├── VMwareVM.cs │ └── VMwareVMSlim.cs ├── Version.cs ├── WebBrowser │ ├── WebBrowser.cs │ ├── WebBrowserElementSearch.cs │ ├── WebBrowserExtensions.cs │ ├── WebBrowserLocation.cs │ └── WebBrowserType.cs ├── WebServer │ ├── WebServer.cs │ ├── WebServerConfig.cs │ └── WebServerExtensions.cs ├── WindowsTaskScheduler │ ├── WindowsTaskScheduler.cs │ ├── WindowsTaskSchedulerExtensions.cs │ ├── WindowsTaskSchedulerPath.cs │ └── WindowsTaskSchedulerTrigger.cs └── Zip.cs ├── MaxRunSoftware.Utilities.Tests ├── AtomicBooleanTests.cs ├── BucketTests.cs ├── Config.cs ├── MaxRunSoftware.Utilities.Tests.csproj ├── MaxRunSoftware.Utilities.Tests.csproj.DotSettings ├── Sql │ └── SqlTests.cs ├── Threading │ ├── ExecutablePoolTests.cs │ └── SingleUseTests.cs └── Usings.cs ├── MaxRunSoftware.Utilities.sln ├── MaxRunSoftware.Utilities.sln.DotSettings ├── MaxRunSoftware.Utilities ├── Buckets │ ├── Bucket.cs │ ├── BucketCache.cs │ ├── BucketCacheThreadSafe.cs │ ├── BucketCacheThreadSafeCopyOnWrite.cs │ ├── BucketExtensions.cs │ ├── BucketStoreBase.cs │ ├── BucketStoreCachedWrapper.cs │ ├── BucketStoreFile.cs │ ├── BucketStoreMemory.cs │ ├── BucketStoreMemoryString.cs │ ├── IBucket.cs │ ├── IBucketReadOnly.cs │ └── IBucketStore.cs ├── Collections │ ├── ComparatorBase.cs │ ├── DictionaryIndexed.cs │ └── DictionaryReadOnlyStringCaseInsensitive.cs ├── Constant.cs ├── Data │ ├── HtmlWriter.cs │ ├── JavaProperties.cs │ ├── JsonWriter.cs │ ├── Table.cs │ ├── TableColumn.cs │ ├── TableColumnCollection.cs │ ├── TableExtensions.cs │ ├── TableRow.cs │ ├── XmlElement.cs │ ├── XmlReader.cs │ └── XmlWriter.cs ├── Extensions │ ├── Extensions.cs │ ├── ExtensionsByte.cs │ ├── ExtensionsCheck.cs │ ├── ExtensionsCollection.cs │ ├── ExtensionsData.cs │ ├── ExtensionsIO.cs │ ├── ExtensionsMethod.cs │ ├── ExtensionsNet.cs │ ├── ExtensionsRandom.cs │ ├── ExtensionsReflection.cs │ ├── ExtensionsStream.cs │ ├── ExtensionsString.cs │ ├── ExtensionsStringConversion.cs │ ├── ExtensionsToString.cs │ └── ExtensionsType.cs ├── Logging │ ├── ILogAppender.cs │ ├── ILogFactory.cs │ ├── ILogger.cs │ ├── LogBackgroundThread.cs │ ├── LogEventArgs.cs │ ├── LogFactory.cs │ ├── LogFactoryExtensions.cs │ ├── LogLevel.cs │ └── LoggerBase.cs ├── MaxRunSoftware.Utilities.csproj ├── MaxRunSoftware.Utilities.csproj.DotSettings ├── Reflection │ ├── ClassReaderWriter.cs │ ├── MissingAttributeException.cs │ ├── PropertyReaderWriter.cs │ └── TypeConverter.cs ├── Sql │ ├── MsSql │ │ ├── SqlMsSql.cs │ │ ├── SqlMsSqlReservedWords.cs │ │ └── SqlMsSqlType.cs │ ├── MySql │ │ ├── SqlMySql.cs │ │ ├── SqlMySqlReservedWords.cs │ │ └── SqlMySqlType.cs │ ├── Oracle │ │ ├── SqlOracle.cs │ │ ├── SqlOracleReservedWords.cs │ │ └── SqlOracleType.cs │ ├── Sql.cs │ ├── SqlDataReaderSchemaColumn.cs │ ├── SqlException.cs │ ├── SqlExtensions.cs │ ├── SqlObject.cs │ ├── SqlParameter.cs │ ├── SqlResult.cs │ ├── SqlType.cs │ └── SqlTypeAttribute.cs ├── Threading │ ├── AtomicBoolean.cs │ ├── ConsumerProducerThread.cs │ ├── ConsumerProducerThreadBase.cs │ ├── ConsumerThread.cs │ ├── ConsumerThreadBase.cs │ ├── ConsumerThreadPool.cs │ ├── ConsumerThreadState.cs │ ├── ExecutablePool.cs │ ├── IntervalThread.cs │ ├── MutexLock.cs │ ├── MutexLockTimeoutException.cs │ ├── SingleUse.cs │ └── ThreadBase.cs ├── Usings.cs ├── Utils │ ├── Util.cs │ ├── UtilBaseConversion.cs │ ├── UtilChangeType.cs │ ├── UtilConsole.cs │ ├── UtilDiagnostic.cs │ ├── UtilEncryption.cs │ ├── UtilEnum.cs │ ├── UtilEquality.cs │ ├── UtilGuid.cs │ ├── UtilHash.cs │ ├── UtilHashCode.cs │ ├── UtilIO.cs │ ├── UtilNet.cs │ ├── UtilReflection.cs │ ├── UtilSerialization.cs │ └── UtilString.cs └── Version.cs ├── README.md ├── publish.sh ├── test.bat ├── test.sh ├── toolbox.png └── toolbox.svg /.idea/.idea.MaxRunSoftware.Utilities/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Rider ignored files 5 | /contentModel.xml 6 | /projectSettingsUpdater.xml 7 | /modules.xml 8 | /.idea.MaxRunSoftware.Utilities.iml 9 | # Editor-based HTTP Client requests 10 | /httpRequests/ 11 | # Datasource local storage ignored files 12 | /dataSources/ 13 | /dataSources.local.xml 14 | -------------------------------------------------------------------------------- /.idea/.idea.MaxRunSoftware.Utilities/.idea/.name: -------------------------------------------------------------------------------- 1 | MaxRunSoftware.Utilities -------------------------------------------------------------------------------- /.idea/.idea.MaxRunSoftware.Utilities/.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /.idea/.idea.MaxRunSoftware.Utilities/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/.idea.MaxRunSoftware.Utilities/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/.idea.MaxRunSoftware.Utilities/.idea/indexLayout.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/.idea.MaxRunSoftware.Utilities/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 38 | -------------------------------------------------------------------------------- /.idea/.idea.MaxRunSoftware.Utilities/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/CommandException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Runtime.Serialization; 17 | 18 | namespace MaxRunSoftware.Utilities.Console; 19 | 20 | public class CommandException : ApplicationException 21 | { 22 | public CommandException() { } 23 | 24 | public CommandException(string message) : base(message) { } 25 | 26 | public CommandException(string message, Exception innerException) : base(message, innerException) { } 27 | 28 | protected CommandException(SerializationInfo info, StreamingContext context) : base(info, context) { } 29 | } 30 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/CommandHelpBuilder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using System.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.Console; 19 | 20 | public class CommandHelpBuilder 21 | { 22 | public CommandHelpBuilder(string name) { Name = name; } 23 | 24 | public string Name { get; } 25 | 26 | private readonly List summary = new(); 27 | public string Summary => summary.FirstOrDefault(); 28 | 29 | private readonly List<(string p1, string p2, string description)> parameters = new(); 30 | public IReadOnlyList<(string p1, string p2, string description)> Parameters => parameters; 31 | 32 | private readonly List values = new(); 33 | public IReadOnlyList Values => values; 34 | 35 | private readonly List details = new(); 36 | public IReadOnlyList Details => details; 37 | 38 | private readonly List examples = new(); 39 | public IReadOnlyList Examples => examples; 40 | 41 | public void AddSummary(string msg) => summary.Add(msg); 42 | 43 | public void AddValue(string msg) => values.Add(msg); 44 | 45 | public void AddDetail(string msg) => details.Add(msg); 46 | 47 | public void AddParameter(string p1, string p2, string description) => parameters.Add((p1, p2, description)); 48 | 49 | public void AddExample(string example) => examples.Add(example.Replace("`", "\"")); 50 | } 51 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryAddGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryAddGroup : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Adds a new group to ActiveDirectory"); 25 | help.AddParameter(nameof(groupType), "gt", "The group type of the new group (" + ActiveDirectoryGroupType.GlobalSecurityGroup + ") " + DisplayEnumOptions()); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " testgroup"); 28 | help.AddExample(HelpExamplePrefix + " -gt=" + ActiveDirectoryGroupType.GlobalSecurityGroup + " testgroup"); 29 | } 30 | 31 | private ActiveDirectoryGroupType groupType; 32 | 33 | protected override void ExecuteInternal(ActiveDirectory ad) 34 | { 35 | groupType = GetArgParameterOrConfigEnum(nameof(groupType), "gt", ActiveDirectoryGroupType.GlobalSecurityGroup); 36 | 37 | var samAccountName = GetArgValueTrimmed(0); 38 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 39 | 40 | log.Debug("Adding group: " + samAccountName); 41 | ad.AddGroup( 42 | samAccountName, 43 | groupType 44 | ); 45 | log.Info("Successfully added group " + samAccountName); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryAddOU.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryAddOU : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Adds a new OU to ActiveDirectory"); 25 | help.AddParameter(nameof(parentOU), "pou", "The parent OU or leave empty to place the new OU at the top level"); 26 | help.AddValue(" "); 27 | help.AddExample(HelpExamplePrefix + " MyNewOU"); 28 | help.AddExample(HelpExamplePrefix + " -pou=Users MyNewOU \"This is my new OU\""); 29 | } 30 | 31 | private string parentOU; 32 | 33 | protected override void ExecuteInternal(ActiveDirectory ad) 34 | { 35 | parentOU = GetArgParameterOrConfig(nameof(parentOU), "pou").TrimOrNull(); 36 | 37 | var newOUName = GetArgValueTrimmed(0); 38 | newOUName.CheckValueNotNull(nameof(newOUName), log); 39 | 40 | var newOUDescription = GetArgValueTrimmed(1); 41 | log.DebugParameter(nameof(newOUDescription), newOUDescription); 42 | 43 | log.Debug("Adding OU: " + newOUName); 44 | ad.AddOU( 45 | newOUName, 46 | parentOU, 47 | newOUDescription 48 | ); 49 | log.Info("Successfully added OU " + newOUName); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryAddUserToGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | // ReSharper disable StringLiteralTypo 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class ActiveDirectoryAddUserToGroup : ActiveDirectoryBase 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | base.CreateHelp(help); 26 | help.AddSummary("Adds a user to the specified group in ActiveDirectory"); 27 | help.AddValue(" "); 28 | help.AddExample(HelpExamplePrefix + " testuser MyGroup1 SomeOtherGroup"); 29 | } 30 | 31 | protected override void ExecuteInternal(ActiveDirectory ad) 32 | { 33 | var values = GetArgValuesTrimmed1N(); 34 | var samAccountName = values.firstValue; 35 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 36 | 37 | var groups = values.otherValues; 38 | log.Debug(groups, nameof(groups)); 39 | if (groups.IsEmpty()) throw ArgsException.ValueNotSpecified(nameof(groups)); 40 | 41 | log.Debug("Adding user " + samAccountName + " to groups " + groups.ToStringDelimited(", ")); 42 | 43 | foreach (var group in groups) 44 | { 45 | log.Debug("Adding user " + samAccountName + " to group " + group); 46 | ad.AddUserToGroup(samAccountName, group); 47 | } 48 | 49 | log.Info("Successfully added user " + samAccountName + " to groups " + groups.ToStringDelimited(", ")); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryChangePassword.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | // ReSharper disable StringLiteralTypo 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class ActiveDirectoryChangePassword : ActiveDirectoryBase 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | base.CreateHelp(help); 26 | help.AddSummary("Changes the password of a user in ActiveDirectory"); 27 | help.AddDetail("Requires LDAPS configured on the server or running on the AD server itself"); 28 | help.AddValue(" "); 29 | help.AddExample(HelpExamplePrefix + " testuser newpassword"); 30 | } 31 | 32 | protected override void ExecuteInternal(ActiveDirectory ad) 33 | { 34 | var samAccountName = GetArgValueTrimmed(0); 35 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 36 | 37 | var newPassword = GetArgValueTrimmed(1); 38 | newPassword.CheckValueNotNull(nameof(newPassword), log); 39 | 40 | log.Debug($"Changing password for user {samAccountName} to {newPassword}"); 41 | ad.ChangePassword(samAccountName, newPassword); 42 | log.Info("Password changed successfully"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryDisableUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryDisableUser : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Disables a user in ActiveDirectory"); 25 | //help.AddDetail("Requires LDAPS configured on the server"); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " testuser"); 28 | } 29 | 30 | protected override void ExecuteInternal(ActiveDirectory ad) 31 | { 32 | var samAccountName = GetArgValueTrimmed(0); 33 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 34 | 35 | log.Debug("Disabling user " + samAccountName); 36 | ad.DisableUser(samAccountName); 37 | log.Info("Successfully disabled user " + samAccountName); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryEnableUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryEnableUser : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Enables a user in ActiveDirectory"); 25 | //help.AddDetail("Requires LDAPS configured on the server"); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " testuser"); 28 | } 29 | 30 | protected override void ExecuteInternal(ActiveDirectory ad) 31 | { 32 | var samAccountName = GetArgValueTrimmed(0); 33 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 34 | 35 | log.Debug("Enabling user " + samAccountName); 36 | ad.EnableUser(samAccountName); 37 | log.Info("Successfully enabled user " + samAccountName); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryList.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | // ReSharper disable StringLiteralTypo 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class ActiveDirectoryList : ActiveDirectoryBase 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | base.CreateHelp(help); 26 | help.AddSummary("Lists all objects and their attributes in an ActiveDirectory to the specified tab delimited file"); 27 | help.AddParameter(nameof(includeExpensiveProperties), "e", "Whether to include expensive properties or not (false)"); 28 | help.AddValue(""); 29 | help.AddExample(HelpExamplePrefix + " adlist.txt"); 30 | } 31 | 32 | private bool includeExpensiveProperties; 33 | 34 | protected override void ExecuteInternal(ActiveDirectory ad) 35 | { 36 | includeExpensiveProperties = GetArgParameterOrConfigBool(nameof(includeExpensiveProperties), "e", false); 37 | var outputFile = GetArgValueTrimmed(0); 38 | outputFile.CheckValueNotNull(nameof(outputFile), log); 39 | 40 | var activeDirectoryObjects = ad.GetAll(); 41 | var t = ActiveDirectoryObject.CreateTable(activeDirectoryObjects, includeExpensiveProperties); 42 | WriteTableTab(outputFile, t); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryListComputers.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryListComputers : ActiveDirectoryListBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | help.AddSummary("Lists all or pattern matched computers in an ActiveDirectory"); 24 | help.AddExample(HelpExamplePrefix); 25 | help.AddExample(HelpExamplePrefix + " ?yComputer*"); 26 | help.AddValue(""); 27 | base.CreateHelp(help); 28 | } 29 | 30 | protected override bool IsValidObject(ActiveDirectoryObject obj) 31 | { 32 | if (!obj.IsComputer) return false; 33 | 34 | if (computerPattern == null) return true; 35 | 36 | return obj.ObjectName.EqualsWildcard(computerPattern, true); 37 | } 38 | 39 | private string computerPattern; 40 | 41 | protected override void ExecuteInternal(ActiveDirectory ad) 42 | { 43 | computerPattern = GetArgValueTrimmed(0); 44 | log.DebugParameter(nameof(computerPattern), computerPattern); 45 | base.ExecuteInternal(ad); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryListGroups.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryListGroups : ActiveDirectoryListBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | help.AddSummary("Lists all or pattern matched groups in an ActiveDirectory"); 24 | help.AddExample(HelpExamplePrefix); 25 | help.AddExample(HelpExamplePrefix + " ?yGroup*"); 26 | help.AddValue(""); 27 | base.CreateHelp(help); 28 | } 29 | 30 | protected override bool IsValidObject(ActiveDirectoryObject obj) 31 | { 32 | if (!obj.IsGroup) return false; 33 | 34 | if (groupPattern == null) return true; 35 | 36 | return obj.ObjectName.EqualsWildcard(groupPattern, true); 37 | } 38 | 39 | private string groupPattern; 40 | 41 | protected override void ExecuteInternal(ActiveDirectory ad) 42 | { 43 | groupPattern = GetArgValueTrimmed(0); 44 | log.DebugParameter(nameof(groupPattern), groupPattern); 45 | base.ExecuteInternal(ad); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryListObjects.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | // ReSharper disable StringLiteralTypo 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class ActiveDirectoryListObjects : ActiveDirectoryListBase 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | help.AddSummary("Lists all or pattern matched objects in an ActiveDirectory"); 26 | help.AddExample(HelpExamplePrefix); 27 | help.AddExample(HelpExamplePrefix + " ?teve*"); 28 | help.AddValue(""); 29 | base.CreateHelp(help); 30 | } 31 | 32 | protected override bool IsValidObject(ActiveDirectoryObject obj) 33 | { 34 | if (objectPattern == null) return true; 35 | 36 | return obj.ObjectName.EqualsWildcard(objectPattern, true); 37 | } 38 | 39 | private string objectPattern; 40 | 41 | protected override void ExecuteInternal(ActiveDirectory ad) 42 | { 43 | objectPattern = GetArgValueTrimmed(0); 44 | log.DebugParameter(nameof(objectPattern), objectPattern); 45 | base.ExecuteInternal(ad); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryListUsers.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | // ReSharper disable StringLiteralTypo 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class ActiveDirectoryListUsers : ActiveDirectoryListBase 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | help.AddSummary("Lists all or pattern matched users in an ActiveDirectory"); 26 | help.AddExample(HelpExamplePrefix); 27 | help.AddExample(HelpExamplePrefix + " ?teve*"); 28 | help.AddValue(""); 29 | base.CreateHelp(help); 30 | } 31 | 32 | protected override bool IsValidObject(ActiveDirectoryObject obj) 33 | { 34 | if (!obj.IsUser) return false; 35 | 36 | if (userPattern == null) return true; 37 | 38 | return obj.ObjectName.EqualsWildcard(userPattern, true); 39 | } 40 | 41 | private string userPattern; 42 | 43 | protected override void ExecuteInternal(ActiveDirectory ad) 44 | { 45 | userPattern = GetArgValueTrimmed(0); 46 | log.DebugParameter(nameof(userPattern), userPattern); 47 | base.ExecuteInternal(ad); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryListUsersOfGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Linq; 16 | using MaxRunSoftware.Utilities.External; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class ActiveDirectoryListUsersOfGroup : ActiveDirectoryListBase 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | help.AddSummary("Lists all user names that are members of the specified group in an ActiveDirectory"); 25 | help.AddValue(""); 26 | help.AddExample(HelpExamplePrefix + " M?Group*"); 27 | base.CreateHelp(help); 28 | } 29 | 30 | protected override bool IsValidObject(ActiveDirectoryObject obj) => obj.IsUser && obj.MemberOfNames.Any(o => o.EqualsWildcard(groupPattern, true)); 31 | 32 | private string groupPattern; 33 | public override string[] DefaultColumnsToInclude => base.DefaultColumnsToInclude.Add(nameof(ActiveDirectoryObject.MemberOfNamesString)); 34 | 35 | protected override void ExecuteInternal(ActiveDirectory ad) 36 | { 37 | groupPattern = GetArgValueTrimmed(0); 38 | groupPattern.CheckValueNotNull(nameof(groupPattern), log); 39 | 40 | base.ExecuteInternal(ad); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryMoveGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryMoveGroup : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Moves a group from one OU to another OU in ActiveDirectory"); 25 | help.AddValue(" "); 26 | help.AddExample(HelpExamplePrefix + " testgroup MyNewOU"); 27 | } 28 | 29 | protected override void ExecuteInternal(ActiveDirectory ad) 30 | { 31 | var samAccountName = GetArgValueTrimmed(0); 32 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 33 | 34 | // ReSharper disable once InconsistentNaming 35 | // ReSharper disable once IdentifierTypo 36 | var newOUSAMAccountName = GetArgValueTrimmed(1); 37 | newOUSAMAccountName.CheckValueNotNull(nameof(newOUSAMAccountName), log); 38 | 39 | log.Debug($"Changing OU of group {samAccountName} to {newOUSAMAccountName}"); 40 | ad.MoveGroup(samAccountName, newOUSAMAccountName); 41 | log.Info($"Group {samAccountName} successfully moved to {newOUSAMAccountName}"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryMoveUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryMoveUser : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Moves a user from one OU to another OU in ActiveDirectory"); 25 | help.AddValue(" "); 26 | help.AddExample(HelpExamplePrefix + " testuser MyNewOU"); 27 | } 28 | 29 | protected override void ExecuteInternal(ActiveDirectory ad) 30 | { 31 | var samAccountName = GetArgValueTrimmed(0); 32 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 33 | 34 | // ReSharper disable once InconsistentNaming 35 | // ReSharper disable once IdentifierTypo 36 | var newOUSAMAccountName = GetArgValueTrimmed(1); 37 | newOUSAMAccountName.CheckValueNotNull(nameof(newOUSAMAccountName), log); 38 | 39 | log.Debug($"Changing OU of user {samAccountName} to {newOUSAMAccountName}"); 40 | ad.MoveUser(samAccountName, newOUSAMAccountName); 41 | log.Info($"User {samAccountName} successfully moved to {newOUSAMAccountName}"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryRemoveGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryRemoveGroup : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Removes a group from ActiveDirectory"); 25 | //help.AddDetail("Requires LDAPS configured on the server"); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " testgroup"); 28 | } 29 | 30 | protected override void ExecuteInternal(ActiveDirectory ad) 31 | { 32 | var values = GetArgValues().TrimOrNull().WhereNotNull(); 33 | 34 | var samAccountName = values.GetAtIndexOrDefault(0).TrimOrNull(); 35 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 36 | 37 | log.Debug("Removing group " + samAccountName); 38 | ad.RemoveGroup(samAccountName); 39 | log.Info("Successfully removed group " + samAccountName); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryRemoveOU.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryRemoveOU : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Removes an OU from ActiveDirectory"); 25 | //help.AddDetail("Requires LDAPS configured on the server"); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " MyOU"); 28 | } 29 | 30 | protected override void ExecuteInternal(ActiveDirectory ad) 31 | { 32 | var ouName = GetArgValueTrimmed(0); 33 | ouName.CheckValueNotNull(nameof(ouName), log); 34 | 35 | log.Debug("Removing OU: " + ouName); 36 | ad.RemoveOU(ouName); 37 | log.Info("Successfully removed OU " + ouName); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryRemoveUser.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryRemoveUser : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Removes a user from ActiveDirectory"); 25 | //help.AddDetail("Requires LDAPS configured on the server"); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " testuser"); 28 | } 29 | 30 | protected override void ExecuteInternal(ActiveDirectory ad) 31 | { 32 | var samAccountName = GetArgValueTrimmed(0); 33 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 34 | 35 | log.Debug("Removing user " + samAccountName); 36 | ad.RemoveUser(samAccountName); 37 | log.Info("Successfully removed user " + samAccountName); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ActiveDirectoryRemoveUserFromGroup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class ActiveDirectoryRemoveUserFromGroup : ActiveDirectoryBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Removes a user from the specified group in ActiveDirectory"); 25 | help.AddValue(" "); 26 | help.AddExample(HelpExamplePrefix + " testuser MyGroup1 SomeOtherGroup"); 27 | } 28 | 29 | protected override void ExecuteInternal(ActiveDirectory ad) 30 | { 31 | var values = GetArgValuesTrimmed1N(); 32 | var samAccountName = values.firstValue; 33 | samAccountName.CheckValueNotNull(nameof(samAccountName), log); 34 | 35 | var groups = values.otherValues; 36 | log.Debug(groups, nameof(groups)); 37 | if (groups.IsEmpty()) throw ArgsException.ValueNotSpecified(nameof(groups)); 38 | 39 | log.Debug("Removing user " + samAccountName + " from groups " + groups.ToStringDelimited(", ")); 40 | foreach (var group in groups) 41 | { 42 | log.Debug("Removing user " + samAccountName + " from group " + group); 43 | ad.RemoveUserFromGroup(samAccountName, group); 44 | } 45 | 46 | log.Info("Successfully removed user " + samAccountName + " from groups " + groups.ToStringDelimited(", ")); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/DirectoryRemoveEmpty.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.IO; 16 | using System.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class DirectoryRemoveEmpty : Command 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | help.AddSummary("Scans all subfolders recursively in target directory and removes any folders that are empty"); 25 | help.AddValue(""); 26 | help.AddExample("MyDirectory"); 27 | } 28 | 29 | protected override void ExecuteInternal() 30 | { 31 | //var encoding = GetArgParameterOrConfigEncoding("encoding", "en"); 32 | var targetDirectory = GetArgValueDirectory(0); 33 | 34 | var subDirectories = Util.FileListDirectories(targetDirectory, true) 35 | .Select(Path.GetFullPath) 36 | .Where(o => o.Length > targetDirectory.Length) 37 | .Where(o => !o.EqualsCaseInsensitive(targetDirectory)) 38 | .OrderBy(o => o.Length) 39 | .Reverse() 40 | .ToList(); 41 | 42 | foreach (var subDirectory in subDirectories) 43 | { 44 | var items = Util.FileList(subDirectory).Where(o => !o.Path.EqualsCaseSensitive(subDirectory)).ToList(); 45 | log.Debug(subDirectory + " [files:" + items.Count(o => !o.IsDirectory) + "] [directories:" + items.Count(o => o.IsDirectory) + "]"); 46 | if (items.IsEmpty()) 47 | { 48 | log.Info("Delete: " + subDirectory); 49 | Directory.Delete(subDirectory); 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/DirectorySize.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using System.Linq; 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class DirectorySize : Command 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | help.AddSummary("Scans all fills and subfolders of a directory to obtain the size of the directory"); 26 | help.AddValue(""); 27 | help.AddExample("MyDirectory"); 28 | } 29 | 30 | protected override void ExecuteInternal() 31 | { 32 | var targetDirectory = GetArgValueDirectory(0); 33 | 34 | log.Debug("Scanning for files: " + targetDirectory); 35 | var files = Util.FileListFiles(targetDirectory, true).ToList(); 36 | log.Debug($"Found {files.Count} files"); 37 | 38 | long totalSize = 0; 39 | foreach (var file in files) 40 | { 41 | var size = Util.FileGetSize(file); 42 | log.Trace(size.ToString().PadLeft(long.MaxValue.ToString().Length + 1) + " " + file); 43 | totalSize += size; 44 | } 45 | 46 | var sizes = new List<(long size, string suffix)> 47 | { 48 | (Constant.BYTES_TERA, "TB"), 49 | (Constant.BYTES_GIGA, "GB"), 50 | (Constant.BYTES_MEGA, "MB"), 51 | (Constant.BYTES_KILO, "KB"), 52 | (-1, "B") 53 | }; 54 | 55 | 56 | foreach (var sz in sizes) 57 | { 58 | if (totalSize < 1) 59 | { 60 | log.Info("0"); 61 | break; 62 | } 63 | 64 | if (totalSize >= sz.size) 65 | { 66 | // ReSharper disable RedundantCast 67 | var newSize = (double)totalSize / (double)sz.size; 68 | // ReSharper restore RedundantCast 69 | newSize = newSize.Round(MidpointRounding.AwayFromZero, 2); 70 | log.Info(newSize + " " + sz.suffix); 71 | break; 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/EncodePassword.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | [SuppressBanner] 18 | public class EncodePassword : Command 19 | { 20 | protected override void CreateHelp(CommandHelpBuilder help) 21 | { 22 | help.AddSummary("Encodes a password to be used in a HUC properties file"); 23 | help.AddValue(""); 24 | help.AddExample(""); 25 | help.AddExample("mySecretPassword"); 26 | } 27 | 28 | protected override void ExecuteInternal() 29 | { 30 | var password = GetArgValueTrimmed(0); 31 | log.DebugParameter(nameof(password), password); 32 | password.CheckValueNotNull(nameof(password), log); 33 | 34 | var encodedPassword = Encrypt(password); 35 | log.Info(encodedPassword); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/FileAppend.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.IO; 16 | 17 | // ReSharper disable StringLiteralTypo 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class FileAppend : Command 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | help.AddSummary("Appends one or more source files to a target file"); 26 | //help.AddParameter("encoding", "en", "Encoding of the input file, ASCII/BIGENDIANUNICODE/DEFAULT/UNICODE/UTF32/UTF8/UTF8BOM (UTF8)"); 27 | help.AddValue(" "); 28 | help.AddExample("mainfile.txt file1.txt file2.txt"); 29 | } 30 | 31 | protected override void ExecuteInternal() 32 | { 33 | //var encoding = GetArgParameterOrConfigEncoding("encoding", "en"); 34 | var values = GetArgValuesTrimmed1N(); 35 | var targetFile = values.firstValue; 36 | targetFile.CheckValueNotNull(nameof(targetFile), log); 37 | targetFile = Path.GetFullPath(targetFile); 38 | log.DebugParameter(nameof(targetFile), targetFile); 39 | 40 | var sourceFiles = values.otherValues; 41 | log.Debug(sourceFiles, nameof(sourceFiles)); 42 | if (values.otherValues.IsEmpty()) throw ArgsException.ValueNotSpecified(nameof(sourceFiles)); 43 | 44 | sourceFiles = ParseInputFiles(values.otherValues); 45 | log.Debug(sourceFiles, nameof(sourceFiles)); 46 | CheckFileExists(sourceFiles); 47 | 48 | using (var targetFileStream = Util.FileOpenWrite(targetFile)) 49 | { 50 | targetFileStream.Seek(targetFileStream.Length, SeekOrigin.Begin); // Set the stream position to the end of the file. 51 | foreach (var sourceFile in sourceFiles) 52 | { 53 | using (var sourceFileStream = Util.FileOpenRead(sourceFile)) 54 | { 55 | log.Debug("Writing file " + sourceFile + " to " + targetFile); 56 | sourceFileStream.CopyTo(targetFileStream, 10 * (int)Constant.BYTES_MEGA); 57 | log.Info(targetFile + " <-- " + sourceFile); 58 | } 59 | } 60 | 61 | targetFileStream.Flush(); 62 | targetFileStream.CloseSafe(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/FileSplit.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.IO; 17 | using System.Linq; 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class FileSplit : Command 22 | { 23 | protected override void CreateHelp(CommandHelpBuilder help) 24 | { 25 | help.AddSummary("Splits a source file into 2 or more target files based on line numbers"); 26 | help.AddValue(" "); 27 | help.AddExample("file.txt file1.txt file2.txt file3.txt"); 28 | help.AddDetail("Note that this function buffers the entire file into memory, so it may require a lot of RAM"); 29 | } 30 | 31 | protected override void ExecuteInternal() 32 | { 33 | //var encoding = GetArgParameterOrConfigEncoding("encoding", "en"); 34 | var values = GetArgValuesTrimmed1N(); 35 | var sourceFile = values.firstValue; 36 | sourceFile.CheckValueNotNull(nameof(sourceFile), log); 37 | sourceFile = Path.GetFullPath(sourceFile); 38 | log.DebugParameter(nameof(sourceFile), sourceFile); 39 | CheckFileExists(sourceFile); 40 | 41 | var targetFiles = values.otherValues.Select(Path.GetFullPath).ToList(); 42 | if (targetFiles.IsEmpty()) throw ArgsException.ValueNotSpecified(nameof(targetFiles)); 43 | 44 | log.Debug(targetFiles, nameof(targetFiles)); 45 | 46 | var sourceFileData = Util.FileRead(sourceFile, Constant.ENCODING_UTF8); 47 | var sourceFileDataLines = sourceFileData.SplitOnNewline(); 48 | // ReSharper disable once RedundantAssignment 49 | sourceFileData = null; 50 | GC.Collect(); 51 | 52 | var parts = sourceFileDataLines.SplitIntoParts(targetFiles.Count); 53 | // ReSharper disable once RedundantAssignment 54 | sourceFileDataLines = null; 55 | GC.Collect(); 56 | 57 | for (var i = 0; i < parts.Length; i++) 58 | { 59 | var part = parts[i]; 60 | var partData = part.ToStringDelimited(Environment.NewLine); 61 | Util.FileWrite(targetFiles[i], partData, Constant.ENCODING_UTF8); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/FtpDelete.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class FtpDelete : FtpBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Deletes a file or files on a FTP/FTPS/SFTP server"); 25 | help.AddValue(" "); 26 | help.AddExample(HelpExamplePrefix + " remotefile.txt"); 27 | help.AddExample(HelpExamplePrefix + " -e=explicit remotefile.txt"); 28 | help.AddExample(HelpExamplePrefix + " -e=implicit remotefile.txt"); 29 | help.AddExample(HelpExamplePrefix + " -e=ssh remotefile.txt"); 30 | } 31 | 32 | protected override void ExecuteInternal() 33 | { 34 | base.ExecuteInternal(); 35 | 36 | var filesToDelete = GetArgValuesTrimmed(); 37 | if (filesToDelete.IsEmpty()) throw ArgsException.ValueNotSpecified(nameof(filesToDelete)); 38 | 39 | log.Debug(filesToDelete, nameof(filesToDelete)); 40 | 41 | using (var c = OpenClient()) 42 | { 43 | foreach (var fileToDelete in filesToDelete) 44 | { 45 | try 46 | { 47 | c.DeleteFile(fileToDelete); 48 | log.Info("Successfully deleted remote file " + fileToDelete); 49 | } 50 | catch (Exception e) { log.Error("Error attempting to delete remote file " + fileToDelete, e); } 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/GenerateKeyPair.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class GenerateKeyPair : Command 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | help.AddSummary("Generates a public/private key pair"); 24 | help.AddParameter(nameof(length), "l", "The RSA key length (1024)"); 25 | help.AddValue(" "); 26 | help.AddExample("MyPublicKey.txt MyPrivateKey.txt"); 27 | help.AddExample("-l=4096 MyPublicKey.txt MyPrivateKey.txt"); 28 | } 29 | 30 | private int length; 31 | 32 | protected override void ExecuteInternal() 33 | { 34 | length = GetArgParameterOrConfigInt(nameof(length), "l", 1024); 35 | 36 | var publicKeyFile = GetArgValueTrimmed(0); 37 | log.Debug(nameof(publicKeyFile), publicKeyFile); 38 | if (publicKeyFile == null) throw new ArgsException(nameof(publicKeyFile), $"No {nameof(publicKeyFile)} specified to save to"); 39 | 40 | var privateKeyFile = GetArgValueTrimmed(1); 41 | log.Debug(nameof(privateKeyFile), privateKeyFile); 42 | if (privateKeyFile == null) throw new ArgsException(nameof(privateKeyFile), $"No {nameof(privateKeyFile)} specified to save to"); 43 | 44 | var keyPair = Encryption.GenerateKeyPair(length); 45 | 46 | WriteFile(publicKeyFile, keyPair.publicKey, Constant.ENCODING_UTF8); 47 | WriteFile(privateKeyFile, keyPair.privateKey, Constant.ENCODING_UTF8); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/GoogleSheetsAddRow.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class GoogleSheetsAddRow : GoogleSheetsBase 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | base.CreateHelp(help); 25 | help.AddSummary("Adds a row of data to a Google Sheet"); 26 | help.AddDetail("For empty values use the keyword NULL instead of a blank"); 27 | help.AddParameter(nameof(sheetName), "s", "The spreadsheet sheet name/tab to upload to (default first sheet)"); 28 | help.AddValue(" "); 29 | // ReSharper disable StringLiteralTypo 30 | help.AddExample("-k=`MyGoogleAppKey.json` -a=`MyApplicationName` -id=`dkjfsd328sdfuhscbjcds8hfjndsfdsfdsfe` AA null CC"); 31 | // ReSharper restore StringLiteralTypo 32 | } 33 | 34 | private string sheetName; 35 | 36 | protected override void ExecuteInternal() 37 | { 38 | base.ExecuteInternal(); 39 | sheetName = GetArgParameterOrConfig(nameof(sheetName), "s"); 40 | 41 | var values = GetArgValues().TrimOrNull().ToList(); 42 | log.Debug(values, nameof(values)); 43 | 44 | for (var i = 0; i < values.Count; i++) 45 | { 46 | if (string.Equals(values[i], "null", StringComparison.OrdinalIgnoreCase)) { values[i] = null; } 47 | } 48 | 49 | using (var c = CreateConnection()) 50 | { 51 | log.Debug("Adding row of data"); 52 | c.AddRow(sheetName, values.ToArray()); 53 | log.Info("Added row: " + string.Join(", ", values)); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/GoogleSheetsBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using MaxRunSoftware.Utilities.External; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public abstract class GoogleSheetsBase : Command 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | help.AddDetail("See the following to setup the account to be able to interact with Google Sheets..."); 25 | // ReSharper disable StringLiteralTypo 26 | help.AddDetail("https://medium.com/@williamchislett/writing-to-google-sheets-api-using-net-and-a-services-account-91ee7e4a291"); 27 | // ReSharper restore StringLiteralTypo 28 | help.AddParameter(nameof(securityKeyFile), "k", "The JSON formatted security key file"); 29 | help.AddParameter(nameof(applicationName), "a", "The Google Developer application name"); 30 | help.AddParameter(nameof(spreadsheetId), "id", "The ID of the spreadsheet to upload to which is in the URL of the document"); 31 | } 32 | 33 | private string securityKeyFile; 34 | private string securityKeyFileData; 35 | private string applicationName; 36 | private string spreadsheetId; 37 | 38 | protected override void ExecuteInternal() 39 | { 40 | securityKeyFile = GetArgParameterOrConfigRequired(nameof(securityKeyFile), "k"); 41 | securityKeyFileData = ReadFile(securityKeyFile); 42 | log.Debug(nameof(securityKeyFileData) + ": " + securityKeyFileData); 43 | 44 | applicationName = GetArgParameterOrConfigRequired(nameof(applicationName), "a"); 45 | spreadsheetId = GetArgParameterOrConfigRequired(nameof(spreadsheetId), "id"); 46 | } 47 | 48 | protected GoogleSheets CreateConnection() 49 | { 50 | if (spreadsheetId == null) throw new Exception("base.Execute() never called for class " + GetType().FullNameFormatted()); 51 | 52 | log.Debug("Opening Google Sheets connection"); 53 | return new GoogleSheets(securityKeyFileData, applicationName, spreadsheetId); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/GoogleSheetsClear.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | public class GoogleSheetsClear : GoogleSheetsBase 18 | { 19 | protected override void CreateHelp(CommandHelpBuilder help) 20 | { 21 | base.CreateHelp(help); 22 | help.AddSummary("Clears all data in a Google Sheet"); 23 | help.AddParameter(nameof(sheetName), "s", "The spreadsheet sheet name/tab to clear (default first sheet)"); 24 | // ReSharper disable StringLiteralTypo 25 | help.AddExample("-k=`MyGoogleAppKey.json` -a=`MyApplicationName` -id=`dkjfsd328sdfuhscbjcds8hfjndsfdsfdsfe` -s=`Sheet1`"); 26 | help.AddExample("-k=`MyGoogleAppKey.json` -a=`MyApplicationName` -id=`dkjfsd328sdfuhscbjcds8hfjndsfdsfdsfe`"); 27 | // ReSharper restore StringLiteralTypo 28 | } 29 | 30 | private string sheetName; 31 | 32 | protected override void ExecuteInternal() 33 | { 34 | base.ExecuteInternal(); 35 | sheetName = GetArgParameterOrConfig(nameof(sheetName), "s"); 36 | 37 | using (var c = CreateConnection()) 38 | { 39 | log.Debug("Clearing sheet"); 40 | c.ClearSheet(sheetName); 41 | log.Info("Cleared sheet"); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/GoogleSheetsQuery.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | public class GoogleSheetsQuery : GoogleSheetsBase 18 | { 19 | protected override void CreateHelp(CommandHelpBuilder help) 20 | { 21 | base.CreateHelp(help); 22 | help.AddSummary("Query a Google Sheet for data and generate a tab delimited file of the data"); 23 | help.AddParameter(nameof(sheetName), "s", "The spreadsheet sheet name/tab to query (default first sheet)"); 24 | help.AddParameter(nameof(range), "r", "The range to query from (A1:ZZ)"); 25 | help.AddValue(""); 26 | // ReSharper disable StringLiteralTypo 27 | help.AddExample("-k=`MyGoogleAppKey.json` -a=`MyApplicationName` -id=`dkjfsd328sdfuhscbjcds8hfjndsfdsfdsfe` MyFile.txt"); 28 | // ReSharper restore StringLiteralTypo 29 | } 30 | 31 | private string sheetName; 32 | private string range; 33 | 34 | protected override void ExecuteInternal() 35 | { 36 | base.ExecuteInternal(); 37 | sheetName = GetArgParameterOrConfig(nameof(sheetName), "s"); 38 | range = GetArgParameterOrConfig(nameof(range), "r", "A1:ZZ"); 39 | 40 | var outputFile = GetArgValueTrimmed(0); 41 | outputFile.CheckValueNotNull(nameof(outputFile), log); 42 | 43 | using (var c = CreateConnection()) 44 | { 45 | log.Debug("Querying sheet"); 46 | var items = c.Query(sheetName, range); 47 | var table = Utilities.Table.Create(items, true); 48 | WriteTableTab(outputFile, table); 49 | log.Info("Sheet with " + items.Count + " rows written to " + outputFile); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/Guid.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | [SuppressBanner] 18 | public class Guid : Command 19 | { 20 | protected override void CreateHelp(CommandHelpBuilder help) 21 | { 22 | help.AddSummary("Generates GUIDs"); 23 | help.AddValue(""); 24 | help.AddExample(""); 25 | help.AddExample("6"); 26 | } 27 | 28 | protected override void ExecuteInternal() 29 | { 30 | var numberOfGuidsString = GetArgValueTrimmed(0) ?? "1"; 31 | var numberOfGuids = numberOfGuidsString.ToInt(); 32 | 33 | for (var i = 0; i < numberOfGuids; i++) log.Info(System.Guid.NewGuid().ToString()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/ShowProperties.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class ShowProperties : Command 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | help.AddSummary("Shows property file definitions"); 25 | help.AddParameter(nameof(showUndefined), "a", "Shows undefined properties too"); 26 | help.AddValue(" | CURRENT"); 27 | help.AddExample(""); 28 | help.AddExample("-a"); 29 | } 30 | 31 | private bool showUndefined; 32 | 33 | protected override void ExecuteInternal() 34 | { 35 | showUndefined = GetArgParameterOrConfigBool(nameof(showUndefined), "s", false); 36 | var propertiesFile = GetArgValueTrimmed(0); 37 | log.DebugParameter(nameof(propertiesFile), propertiesFile); 38 | 39 | var configFile = propertiesFile == null ? new ConfigFile() : new ConfigFile(propertiesFile); 40 | 41 | var keys = new List(); 42 | 43 | if (showUndefined) keys.AddRange(ConfigFile.GetAllKeys()); 44 | 45 | var set = new HashSet(keys, StringComparer.OrdinalIgnoreCase); 46 | foreach (var key in configFile.Keys) 47 | { 48 | if (set.Add(key)) { keys.Add(key); } 49 | } 50 | 51 | foreach (var prop in keys) log.Info(prop + "=" + configFile[prop]); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/Sql.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.IO; 16 | using System.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class Sql : SqlQueryBase 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | base.CreateHelp(help); 25 | help.AddSummary("Execute a SQL statement and/or script and optionally save the result(s) to a tab delimited file(s)"); 26 | help.AddValue(" "); 27 | help.AddExample(HelpExamplePrefix + " -s=`SELECT TOP 100 * FROM Orders` Orders100.txt"); 28 | help.AddExample(HelpExamplePrefix + " -s=`SELECT * FROM Orders; SELECT * FROM Employees` Orders.txt Employees.txt"); 29 | // ReSharper disable StringLiteralTypo 30 | help.AddExample(HelpExamplePrefix + " -f=`mssqlscript.sql` OrdersFromScript.txt"); 31 | // ReSharper restore StringLiteralTypo 32 | } 33 | 34 | protected override void ExecuteInternal() 35 | { 36 | var resultFiles = GetArgValuesTrimmed(); 37 | for (var i = 0; i < resultFiles.Count; i++) 38 | { 39 | if (resultFiles[i] == null) continue; 40 | 41 | resultFiles[i] = Path.GetFullPath(resultFiles[i]); 42 | DeleteExistingFile(resultFiles[i]); 43 | } 44 | 45 | for (var i = 0; i < resultFiles.Count; i++) log.Debug($"resultFiles[{i}]: {resultFiles[i]}"); 46 | 47 | var tables = ExecuteTables(); 48 | 49 | for (var i = 0; i < tables.Length; i++) 50 | { 51 | var table = tables[i]; 52 | var rf = resultFiles.ElementAtOrDefault(i); 53 | 54 | if (rf != null) WriteTableTab(rf, table); 55 | } 56 | 57 | log.Debug("SQL completed"); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/TableBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Text; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public abstract class TableBase : Command 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | help.AddParameter(nameof(encoding), "en", "Encoding of the input table " + DisplayEnumOptions(FileEncoding.UTF8)); 24 | help.AddValue(" "); 25 | } 26 | 27 | protected string CurrentOutputFile { get; private set; } 28 | 29 | private Encoding encoding; 30 | 31 | protected override void ExecuteInternal() 32 | { 33 | encoding = GetArgParameterOrConfigEncoding(nameof(encoding), "en"); 34 | 35 | var inputFiles = ParseInputFiles(GetArgValuesTrimmed()); 36 | if (inputFiles.Count < 1) throw new ArgsException(nameof(inputFiles), $"No <{nameof(inputFiles)}> supplied"); 37 | 38 | log.Debug(inputFiles, nameof(inputFiles)); 39 | CheckFileExists(inputFiles); 40 | 41 | foreach (var includedItem in inputFiles) 42 | { 43 | log.Debug($"Reading table file: {includedItem}"); 44 | var table = ReadTableTab(includedItem, encoding); 45 | var outputFile = includedItem; 46 | log.DebugParameter(nameof(outputFile), outputFile); 47 | CurrentOutputFile = outputFile; 48 | DeleteExistingFile(outputFile); 49 | 50 | log.Debug("Writing file with " + table.Columns.Count + " columns and " + table.Count + " rows to file " + outputFile); 51 | 52 | var data = Convert(table); 53 | WriteFile(outputFile, data); 54 | 55 | log.Info("File with " + table.Columns.Count + " columns, " + table.Count + " rows created: " + outputFile); 56 | } 57 | } 58 | 59 | protected abstract string Convert(Utilities.Table table); 60 | } 61 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/TableJson.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | public class TableJson : TableBase 18 | { 19 | protected override void CreateHelp(CommandHelpBuilder help) 20 | { 21 | base.CreateHelp(help); 22 | help.AddSummary("Converts a tab delimited data file to a JSON file"); 23 | help.AddExample("Orders.json"); 24 | } 25 | 26 | protected override string Convert(Utilities.Table table) => table.ToJson(); 27 | } 28 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/TableTranspose.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | public class TableTranspose : TableBase 18 | { 19 | protected override void CreateHelp(CommandHelpBuilder help) 20 | { 21 | base.CreateHelp(help); 22 | help.AddSummary("Switches columns and rows in a tab delimited data file"); 23 | help.AddExample("Orders.txt"); 24 | } 25 | 26 | protected override string Convert(Utilities.Table table) => WriteTableTab(table.Transpose()); 27 | } 28 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/TableXml.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | public class TableXml : TableBase 18 | { 19 | protected override void CreateHelp(CommandHelpBuilder help) 20 | { 21 | base.CreateHelp(help); 22 | help.AddSummary("Converts a tab delimited data file to a XML file"); 23 | help.AddExample("Orders.xml"); 24 | } 25 | 26 | protected override string Convert(Utilities.Table table) => table.ToXml(); 27 | } 28 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/Time.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Globalization; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class Time : Command 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | help.AddSummary("Retrieves the current time from the internet"); 25 | help.AddParameter(nameof(drift), "d", "Show the difference between internet time and local time (false)"); 26 | help.AddExample(""); 27 | help.AddExample("-d"); 28 | } 29 | 30 | private bool drift; 31 | 32 | protected override void ExecuteInternal() 33 | { 34 | drift = GetArgParameterOrConfigBool(nameof(drift), "d", false); 35 | 36 | var internetTime = Util.NetGetInternetDateTime(); 37 | // Strip milliseconds 38 | internetTime = DateTime.ParseExact(internetTime.ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); 39 | 40 | var localTime = DateTime.Now; 41 | // Strip milliseconds 42 | localTime = DateTime.ParseExact(localTime.ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); 43 | 44 | 45 | if (!drift) { log.Info(internetTime.ToString("yyyy-MM-dd HH:mm:ss")); } 46 | else 47 | { 48 | log.Info("Remote: " + internetTime.ToString("yyyy-MM-dd HH:mm:ss")); 49 | log.Info("Local: " + localTime.ToString("yyyy-MM-dd HH:mm:ss")); 50 | var dr = internetTime - localTime; 51 | var msg = "Drift: "; 52 | if (dr.Ticks < 0) { msg = msg + "+"; } 53 | else if (dr.Ticks > 0) msg = msg + "-"; 54 | 55 | msg = msg + dr.Duration().TotalSeconds.Round(MidpointRounding.AwayFromZero, 0); 56 | msg = msg + " seconds"; 57 | log.Info(msg); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/VMwareBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using MaxRunSoftware.Utilities.External; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public abstract class VMwareBase : Command 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | help.AddParameter(nameof(host), "h", "VMware server host name or IP"); 25 | help.AddParameter(nameof(username), "u", "VMware server username"); 26 | help.AddParameter(nameof(password), "p", "VMware server password"); 27 | } 28 | 29 | protected string HelpExamplePrefix => "-h=192.168.1.5 -u=testuser@vsphere.local -p=testpass"; 30 | 31 | private string host; 32 | private string username; 33 | private string password; 34 | 35 | protected override void ExecuteInternal() 36 | { 37 | host = GetArgParameterOrConfigRequired(nameof(host), "h"); 38 | username = GetArgParameterOrConfig(nameof(username), "u"); 39 | password = GetArgParameterOrConfig(nameof(password), "p"); 40 | 41 | using (var vmware = GetVMware()) { ExecuteInternal(vmware); } 42 | } 43 | 44 | protected abstract void ExecuteInternal(VMwareClient vmware); 45 | 46 | protected VMwareClient GetVMware() 47 | { 48 | if (host == null) throw new Exception("base.Execute() never called for class " + GetType().FullNameFormatted()); 49 | 50 | return new VMwareClient(host, username, password); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/VMwareListJSON.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | using Newtonsoft.Json; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class VMwareListJSON : VMwareBase 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | base.CreateHelp(help); 25 | help.AddSummary("Lists all details available for a VMware VCenter environment to a JSON file"); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " MyVMwareStuff.json"); 28 | } 29 | 30 | protected override void ExecuteInternal(VMwareClient vmware) 31 | { 32 | var outputFile = GetArgValueTrimmed(0); 33 | outputFile.CheckValueNotNull(nameof(outputFile), log); 34 | 35 | DeleteExistingFile(outputFile); 36 | 37 | var data = JsonConvert.SerializeObject(vmware, Formatting.Indented); 38 | 39 | Util.FileWrite(outputFile, data, Constant.ENCODING_UTF8); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/VMwareQuery.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | [SuppressBanner] 20 | public class VMwareQuery : VMwareBase 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | base.CreateHelp(help); 25 | help.AddSummary("Queries a VMware path for REST data"); 26 | help.AddValue(""); 27 | help.AddExample(HelpExamplePrefix + " /rest/vcenter/vm"); 28 | help.AddDetail("https://developer.vmware.com/docs/vsphere-automation/latest/vcenter/index.html"); 29 | } 30 | 31 | protected override void ExecuteInternal(VMwareClient vmware) 32 | { 33 | var path = GetArgValueTrimmed(0); 34 | path.CheckValueNotNull(nameof(path), log); 35 | 36 | var obj = vmware.Get(path); 37 | var json = VMwareClient.FormatJson(obj); 38 | log.Info(json); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/WGet.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.IO; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class WGet : Command 21 | { 22 | protected override void CreateHelp(CommandHelpBuilder help) 23 | { 24 | help.AddSummary("Same as WGET command for getting web resources"); 25 | help.AddParameter(nameof(username), "u", "Basic authentication username"); 26 | help.AddParameter(nameof(password), "p", "Basic authentication password"); 27 | help.AddValue(" "); 28 | help.AddExample("https://github.com/maxrunsoftware/huc/releases/download/v" + Version.Value + "/huc-linux.zip"); 29 | help.AddExample("https://github.com github.txt"); 30 | } 31 | 32 | private string username; 33 | private string password; 34 | 35 | protected override void ExecuteInternal() 36 | { 37 | username = GetArgParameterOrConfig(nameof(username), "u").TrimOrNull(); 38 | password = GetArgParameterOrConfig(nameof(password), "p").TrimOrNull(); 39 | 40 | var sourceUrl = GetArgValueTrimmed(0); 41 | sourceUrl.CheckValueNotNull(nameof(sourceUrl), log); 42 | 43 | var outputFile = GetArgValueTrimmed(1); 44 | log.DebugParameter(nameof(outputFile), outputFile); 45 | outputFile ??= Path.Combine(Environment.CurrentDirectory, Util.WebParseFilename(sourceUrl)); 46 | outputFile = Path.GetFullPath(outputFile); 47 | log.DebugParameter(nameof(outputFile), outputFile); 48 | DeleteExistingFile(outputFile); 49 | 50 | Util.WebDownload(sourceUrl, outputFile, username, password); 51 | log.Info("File downloaded: " + outputFile); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/WebServer.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | public class WebServer : WebServerBase 18 | { 19 | protected override void CreateHelp(CommandHelpBuilder help) 20 | { 21 | base.CreateHelp(help); 22 | 23 | help.AddSummary("Creates a web server to host static html files"); 24 | help.AddDetail("You can use an index.html file in the root of the directory to display a page rather then a directory listing"); 25 | help.AddValue(""); 26 | help.AddExample("."); 27 | help.AddExample("-o=80 c:\\www"); 28 | } 29 | 30 | protected override void ExecuteInternal() 31 | { 32 | base.ExecuteInternal(); 33 | 34 | var directoryToServe = GetArgValueDirectory(0, "directoryToServe", useCurrentDirectoryAsDefault: true); 35 | 36 | var config = GetConfig(); 37 | config.DirectoryToServe = directoryToServe; 38 | config.DirectoryToServeUrlPath = "/"; 39 | 40 | log.Info("Serving file from " + directoryToServe); 41 | LoopUntilKey(config); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/WebServerUtilityEncryptFile.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Linq; 16 | using EmbedIO; 17 | using MaxRunSoftware.Utilities.External; 18 | 19 | namespace MaxRunSoftware.Utilities.Console.Commands; 20 | 21 | public class WebServerUtilityEncryptFile : WebServerUtilityBase 22 | { 23 | public override HttpVerbs Verbs => HttpVerbs.Any; 24 | 25 | public override string HandleHtml() 26 | { 27 | var html = new HtmlWriter(); 28 | html.Title = "Encrypt File"; 29 | var files = Files; 30 | var password = GetParameterString("password").TrimOrNull(); 31 | if (files.Count == 0 || password == null) 32 | { 33 | html.Form("?"); 34 | html.P(); 35 | html.InputPassword("password", "Password "); 36 | html.PEnd(); 37 | html.P("Click on the 'Choose File' button to upload a file"); 38 | html.InputFile("file"); 39 | html.InputSubmit("Encrypt"); 40 | html.FormEnd(); 41 | } 42 | else 43 | { 44 | var file = files.First(); 45 | var fileName = file.Key; 46 | var fileData = file.Value; 47 | var encryptedBytes = Encryption.Encrypt(Constant.ENCODING_UTF8.GetBytes(password), fileData); 48 | Context.SendFile(encryptedBytes, fileName); 49 | html.P("File encrypted"); 50 | } 51 | 52 | return html.ToString(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/WebServerUtilityGenerateKeyPair.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using MaxRunSoftware.Utilities.External; 17 | 18 | namespace MaxRunSoftware.Utilities.Console.Commands; 19 | 20 | public class WebServerUtilityGenerateKeyPair : WebServerUtilityBase 21 | { 22 | public (bool success, string publicKey, string privateKey) Handle() 23 | { 24 | var lengthN = GetParameterInt("length"); 25 | if (lengthN == null) return (false, null, null); 26 | 27 | var length = lengthN.Value; 28 | 29 | var keyPair = Encryption.GenerateKeyPair(length); 30 | return (true, keyPair.publicKey, keyPair.privateKey); 31 | } 32 | 33 | public override string HandleHtml() 34 | { 35 | try 36 | { 37 | var result = Handle(); 38 | 39 | var html = @" 40 |
41 |

42 | 43 | 44 |

45 | 46 | 47 |

48 | 49 |

50 |
51 | "; 52 | if (result.success) 53 | { 54 | html += $@" 55 |

56 |

Public Key

57 | 58 |

59 | 60 |

Private Key

61 | 62 | "; 63 | } 64 | 65 | return External.WebServer.HtmlMessage("Asymmetric Key Pair", html.Replace("'", "\"")); 66 | } 67 | catch (Exception e) { return External.WebServer.HtmlMessage(e.GetType().FullNameFormatted(), e.ToString()); } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/WebServerUtilityGenerateRandomFile.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class WebServerUtilityGenerateRandomFile : WebServerUtilityBase 20 | { 21 | public string Handle() 22 | { 23 | var generateRandom = new WebServerUtilityGenerateRandom(); 24 | var randomString = (string)generateRandom.Handle(Context); 25 | Context.SendFile(randomString, "random.txt"); 26 | return "Generated Random File"; 27 | } 28 | 29 | public override string HandleHtml() => Handle(); 30 | } 31 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/WindowsTaskSchedulerRemove.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using MaxRunSoftware.Utilities.External; 16 | 17 | namespace MaxRunSoftware.Utilities.Console.Commands; 18 | 19 | public class WindowsTaskSchedulerRemove : WindowsTaskSchedulerBase 20 | { 21 | protected override void CreateHelp(CommandHelpBuilder help) 22 | { 23 | base.CreateHelp(help); 24 | help.AddSummary("Deletes a task from the Windows Task Scheduler"); 25 | help.AddValue(""); 26 | help.AddExample(HelpExamplePrefix + " MyTask"); 27 | } 28 | 29 | protected override void ExecuteInternal() 30 | { 31 | base.ExecuteInternal(); 32 | 33 | var taskPath = GetArgValueTrimmed(0); 34 | if (taskPath == null) throw ArgsException.ValueNotSpecified(nameof(taskPath)); 35 | 36 | using (var scheduler = GetTaskScheduler()) 37 | { 38 | var t = scheduler.GetTask(taskPath); 39 | if (t == null) throw new ArgsException(nameof(taskPath), "Task does not exist " + taskPath); 40 | 41 | log.Debug("Deleting task " + t.GetPath()); 42 | scheduler.TaskDelete(t); 43 | log.Info("Successfully deleted task " + t.GetPath()); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Commands/Xslt.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console.Commands; 16 | 17 | public class Xslt : Command 18 | { 19 | protected override void CreateHelp(CommandHelpBuilder help) 20 | { 21 | help.AddSummary("Applies an XSLT transform to an XML file"); 22 | // ReSharper disable once StringLiteralTypo 23 | help.AddExample("mytransform.xslt myxml.xml"); 24 | help.AddValue(" "); 25 | } 26 | 27 | protected override void ExecuteInternal() 28 | { 29 | var xsltFile = GetArgValueTrimmed(0); 30 | xsltFile.CheckValueNotNull(nameof(xsltFile), log); 31 | var xsltContent = ReadFile(xsltFile); 32 | 33 | var xmlFile = GetArgValueTrimmed(1); 34 | xmlFile.CheckValueNotNull(nameof(xmlFile), log); 35 | var xmlFiles = ParseInputFiles(xmlFile.Yield()); 36 | log.Debug(xmlFiles, nameof(xmlFiles)); 37 | 38 | foreach (var xml in xmlFiles) 39 | { 40 | var xmlContent = ReadFile(xml); 41 | var data = XmlWriter.ApplyXslt(xsltContent, xmlContent); 42 | WriteFile(xml, data); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Encoding.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console; 16 | 17 | public enum FileEncoding 18 | { 19 | ASCII, 20 | BigEndianUnicode, 21 | Default, 22 | Unicode, 23 | UTF32, 24 | UTF8, 25 | UTF8BOM 26 | } 27 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Extensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | 17 | namespace MaxRunSoftware.Utilities.Console; 18 | 19 | public static class Extensions 20 | { 21 | public static void Debug(this ILogger log, IEnumerable enumerable, string name) 22 | { 23 | if (enumerable == null) return; 24 | 25 | var list = new List(enumerable); 26 | for (var i = 0; i < list.Count; i++) log.Debug(name + "[" + i + "]: " + list[i]); 27 | } 28 | 29 | public static void DebugParameter(this ILogger log, string parameterName, object parameterValue) => log.Debug(parameterName + ": " + parameterValue); 30 | 31 | public static string CheckValueNotNull(this string val, string valName, ILogger log) 32 | { 33 | log.DebugParameter(valName, val); 34 | if (val == null) throw ArgsException.ValueNotSpecified(valName); 35 | 36 | return val; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/ICommand.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console; 16 | 17 | public interface ICommand 18 | { 19 | string Name { get; } 20 | string[] Args { get; set; } 21 | void Execute(); 22 | string HelpSummary { get; } 23 | string HelpDetails { get; } 24 | bool IsHidden { get; } 25 | bool SuppressBanner { get; } 26 | } 27 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxrunsoftware/huc/35d4f91a2503005c5946fa805079a436534c6f04/MaxRunSoftware.Utilities.Console/Icon.ico -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/MaxRunSoftware.Utilities.Console.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 1.13.1 7 | Misc command line helper utilities 8 | MaxRunSoftware.Utilities.Console.Program 9 | Icon.ico 10 | 11 | 12 | 13 | 4 14 | 1701;1702;CA1416 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Console/Version.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Console; 16 | 17 | public static class Version 18 | { 19 | public static string Value => Utilities.Version.Value; 20 | } 21 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/ActiveDirectory/ActiveDirectoryGroupType.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.External; 16 | 17 | /// 18 | /// GroupType enumerates the type of group objects in Active Directory. 19 | /// 20 | public enum ActiveDirectoryGroupType 21 | { 22 | /// 23 | /// Specifies a group that can contain accounts from the domain and other global 24 | /// groups from the same domain. This type of group can be exported to a different 25 | /// domain. 26 | /// 27 | GlobalDistributionGroup = 2, 28 | 29 | /// 30 | /// Specifies a group that can contain accounts from any domain, other domain 31 | /// local groups from the same domain, global groups from any domain, and 32 | /// universal groups. This type of group should not be included in access-control 33 | /// lists of resources in other domains. This type of group is intended for use 34 | /// with the LDAP provider. 35 | /// 36 | LocalDistributionGroup = 4, 37 | 38 | /// 39 | /// Specifies a group that can contain accounts from any domain, global 40 | /// groups from any domain, and other universal groups. This type of group 41 | /// cannot contain domain local groups. 42 | /// 43 | UniversalDistributionGroup = 8, 44 | 45 | GlobalSecurityGroup = -2147483646, 46 | 47 | LocalSecurityGroup = -2147483644, 48 | 49 | BuiltInGroup = -2147483643, 50 | 51 | UniversalSecurityGroup = -2147483640 52 | } 53 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/Ftp/FtpClientFile.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.External; 16 | 17 | public class FtpClientFile 18 | { 19 | public string Name { get; } 20 | 21 | public string FullName { get; } 22 | 23 | public FtpClientFileType Type { get; } 24 | 25 | public FtpClientFile(string name, string fullName, FtpClientFileType type) 26 | { 27 | Name = name; 28 | FullName = fullName; 29 | Type = type; 30 | } 31 | 32 | /// 33 | /// Checks to see if our FullName matches a pathOrPattern value. 34 | /// if FullName=/dir1/file1.txt pathOrPattern=/*/file?.txt isCaseSensitive=true IsMatch=true 35 | /// if FullName=/dir1/file1.txt pathOrPattern=/*/FILE?.TXT isCaseSensitive=true IsMatch=false 36 | /// 37 | /// 38 | /// 39 | /// 40 | public bool IsMatch(string pathOrPattern, bool isCaseSensitive) 41 | { 42 | pathOrPattern = pathOrPattern.CheckNotNullTrimmed(nameof(pathOrPattern)); 43 | var source = pathOrPattern.StartsWith("/") ? FullName : Name; 44 | return source.EqualsWildcard(pathOrPattern, !isCaseSensitive); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/Ftp/FtpClientFileType.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.External; 16 | 17 | public enum FtpClientFileType 18 | { 19 | Unknown, 20 | Directory, 21 | File, 22 | Link 23 | } 24 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/Ftp/FtpClientFtpSEncryptionMode.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.External; 16 | 17 | public enum FtpClientFtpSEncryptionMode 18 | { 19 | Explicit, 20 | Implicit 21 | } 22 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/Ftp/IFtpClient.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | 18 | namespace MaxRunSoftware.Utilities.External; 19 | 20 | public interface IFtpClient : IDisposable 21 | { 22 | string ServerInfo { get; } 23 | 24 | string WorkingDirectory { get; } 25 | 26 | void GetFile(string remoteFile, string localFile); 27 | 28 | void PutFile(string remoteFile, string localFile); 29 | 30 | void DeleteFile(string remoteFile); 31 | 32 | IEnumerable ListFiles(string remotePath); 33 | } 34 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/GitHub.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using System.Threading.Tasks; 17 | using Octokit; 18 | 19 | namespace MaxRunSoftware.Utilities.External; 20 | 21 | public class GitHub 22 | { 23 | private readonly string username; 24 | private readonly string repositoryName; 25 | 26 | public GitHub(string username, string repositoryName) 27 | { 28 | this.username = username.CheckNotNullTrimmed(nameof(username)); 29 | this.repositoryName = repositoryName.CheckNotNullTrimmed(nameof(repositoryName)); 30 | } 31 | 32 | public IReadOnlyList Releases 33 | { 34 | get 35 | { 36 | // https://api.github.com/repos/maxrunsoftware/huc/releases 37 | var releasesTask = Task.Run(async () => await GetReleasesAsync()); 38 | var releases = releasesTask.Result; 39 | return releases; 40 | } 41 | } 42 | 43 | private async Task> GetReleasesAsync() 44 | { 45 | var client = new GitHubClient(new ProductHeaderValue(username)); 46 | 47 | var result = await client.Repository.Release.GetAll(username, repositoryName); 48 | return result; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/Ldap/LdapExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.DirectoryServices; 17 | using System.DirectoryServices.AccountManagement; 18 | using System.Reflection; 19 | using System.Text; 20 | 21 | namespace MaxRunSoftware.Utilities.External; 22 | 23 | public static class LdapExtensions 24 | { 25 | private static readonly ILogger log = Logging.LogFactory.GetLogger(MethodBase.GetCurrentMethod()!.DeclaringType); 26 | 27 | private static string ToStringDebugOutput(object o) 28 | { 29 | var sb = new StringBuilder(); 30 | foreach (var prop in ClassReaderWriter.GetProperties(o.GetType(), true, isInstance: true)) 31 | { 32 | object val = null; 33 | try { val = prop.GetValue(o); } 34 | catch (Exception e) { log.Debug("Error retrieving property " + o.GetType().FullNameFormatted() + "." + prop.Name, e); } 35 | 36 | sb.AppendLine(" " + prop.Name + ": " + val.ToStringGuessFormat()); 37 | } 38 | 39 | return sb.ToString(); 40 | } 41 | 42 | public static string ToStringDebug(this DirectoryEntry entry) => ToStringDebugOutput(entry); 43 | 44 | public static string ToStringDebug(this DirectorySearcher searcher) => ToStringDebugOutput(searcher); 45 | 46 | public static string ToStringDebug(this PrincipalContext context) => ToStringDebugOutput(context); 47 | } 48 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/Logging.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.External; 16 | 17 | internal class Logging 18 | { 19 | public static ILogFactory LogFactory => Utilities.LogFactory.LogFactoryImpl; 20 | } 21 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/MaxRunSoftware.Utilities.External.csproj.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True 4 | True 5 | True 6 | True 7 | True 8 | True -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/VMware/VMwareDatacenter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using Newtonsoft.Json.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.External; 19 | 20 | public class VMwareDatacenter : VMwareObject 21 | { 22 | public string Name { get; } 23 | public string Datacenter { get; } 24 | public string DatastoreFolder { get; } 25 | public string HostFolder { get; } 26 | public string NetworkFolder { get; } 27 | public string VMFolder { get; } 28 | 29 | public VMwareDatacenter(VMwareClient vmware, JToken obj) 30 | { 31 | Name = obj.ToString("name"); 32 | Datacenter = obj.ToString("datacenter"); 33 | 34 | obj = QueryValueObjectSafe(vmware, "/rest/vcenter/datacenter/" + Datacenter); 35 | if (obj != null) 36 | { 37 | DatastoreFolder = obj.ToString("datastore_folder"); 38 | HostFolder = obj.ToString("host_folder"); 39 | NetworkFolder = obj.ToString("network_folder"); 40 | VMFolder = obj.ToString("vm_folder"); 41 | } 42 | } 43 | 44 | public static IEnumerable Query(VMwareClient vmware) 45 | { 46 | foreach (var obj in vmware.GetValueArray("/rest/vcenter/datacenter")) yield return new VMwareDatacenter(vmware, obj); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/VMware/VMwareDatastore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using Newtonsoft.Json.Linq; 17 | 18 | // ReSharper disable RedundantCast 19 | 20 | namespace MaxRunSoftware.Utilities.External; 21 | 22 | public class VMwareDatastore : VMwareObject 23 | { 24 | public string Name { get; } 25 | public string Datastore { get; } 26 | public string Type { get; } 27 | public long? FreeSpace { get; } 28 | public long? Capacity { get; } 29 | public long? Used => FreeSpace == null || Capacity == null ? null : Capacity.Value - FreeSpace.Value; 30 | public byte? PercentFree => FreeSpace == null || Capacity == null ? null : (byte)((double)FreeSpace.Value / (double)Capacity.Value * (double)100); 31 | public byte? PercentUsed => PercentFree == null ? null : (byte)((double)100 - (double)PercentFree.Value); 32 | 33 | public bool? Accessible { get; } 34 | public bool? MultipleHostAccess { get; } 35 | public bool? ThinProvisioningSupported { get; } 36 | 37 | public VMwareDatastore(VMwareClient vmware, JToken obj) 38 | { 39 | Name = obj.ToString("name"); 40 | Datastore = obj.ToString("datastore"); 41 | Type = obj.ToString("type"); 42 | FreeSpace = obj.ToLong("free_space"); 43 | Capacity = obj.ToLong("capacity"); 44 | 45 | obj = QueryValueObjectSafe(vmware, "/rest/vcenter/datastore/" + Datastore); 46 | if (obj != null) 47 | { 48 | Accessible = obj.ToBool("accessible"); 49 | MultipleHostAccess = obj.ToBool("multiple_host_access"); 50 | ThinProvisioningSupported = obj.ToBool("thin_provisioning_supported"); 51 | } 52 | } 53 | 54 | public static IEnumerable Query(VMwareClient vmware) 55 | { 56 | foreach (var obj in vmware.GetValueArray("/rest/vcenter/datastore")) yield return new VMwareDatastore(vmware, obj); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/VMware/VMwareFolder.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using Newtonsoft.Json.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.External; 19 | 20 | public class VMwareFolder : VMwareObject 21 | { 22 | public string Name { get; } 23 | public string Folder { get; } 24 | public string Type { get; } 25 | 26 | // ReSharper disable once UnusedParameter.Local 27 | public VMwareFolder(VMwareClient vmware, JToken obj) 28 | { 29 | Name = obj.ToString("name"); 30 | Folder = obj.ToString("folder"); 31 | Type = obj.ToString("type"); 32 | } 33 | 34 | public static IEnumerable Query(VMwareClient vmware) 35 | { 36 | foreach (var obj in vmware.GetValueArray("/rest/vcenter/folder")) yield return new VMwareFolder(vmware, obj); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/VMware/VMwareHost.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using Newtonsoft.Json.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.External; 19 | 20 | public class VMwareHost : VMwareObject 21 | { 22 | public enum HostPowerState 23 | { 24 | Unknown, 25 | PoweredOn, 26 | PoweredOff, 27 | Standby 28 | } 29 | 30 | public enum HostConnectionState 31 | { 32 | Unknown, 33 | Connected, 34 | Disconnected, 35 | NotResponding 36 | } 37 | 38 | public string Name { get; } 39 | public string Host { get; } 40 | public HostConnectionState ConnectionState { get; } 41 | public HostPowerState PowerState { get; } 42 | 43 | // ReSharper disable once UnusedParameter.Local 44 | public VMwareHost(VMwareClient vmware, JToken obj) 45 | { 46 | Name = obj.ToString("name"); 47 | Host = obj.ToString("host"); 48 | 49 | var connectionState = obj.ToString("connection_state"); 50 | if (connectionState == null) { ConnectionState = HostConnectionState.Unknown; } 51 | else if (connectionState.EqualsCaseInsensitive("CONNECTED")) { ConnectionState = HostConnectionState.Connected; } 52 | else if (connectionState.EqualsCaseInsensitive("DISCONNECTED")) { ConnectionState = HostConnectionState.Disconnected; } 53 | else if (connectionState.EqualsCaseInsensitive("NOT_RESPONDING")) ConnectionState = HostConnectionState.NotResponding; 54 | 55 | var powerState = obj.ToString("power_state"); 56 | if (powerState == null) { PowerState = HostPowerState.Unknown; } 57 | else if (powerState.EqualsCaseInsensitive("POWERED_OFF")) { PowerState = HostPowerState.PoweredOff; } 58 | else if (powerState.EqualsCaseInsensitive("POWERED_ON")) { PowerState = HostPowerState.PoweredOn; } 59 | else if (powerState.EqualsCaseInsensitive("STANDBY")) PowerState = HostPowerState.Standby; 60 | } 61 | 62 | public static IEnumerable Query(VMwareClient vmware) 63 | { 64 | foreach (var obj in vmware.GetValueArray("/rest/vcenter/host")) yield return new VMwareHost(vmware, obj); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/VMware/VMwareNetwork.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using Newtonsoft.Json.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.External; 19 | 20 | public class VMwareNetwork : VMwareObject 21 | { 22 | public string Name { get; } 23 | public string Network { get; } 24 | public string Type { get; } 25 | 26 | // ReSharper disable once UnusedParameter.Local 27 | public VMwareNetwork(VMwareClient vmware, JToken obj) 28 | { 29 | Name = obj.ToString("name"); 30 | Network = obj.ToString("network"); 31 | Type = obj.ToString("type"); 32 | } 33 | 34 | public static IEnumerable Query(VMwareClient vmware) 35 | { 36 | foreach (var obj in vmware.GetValueArray("/rest/vcenter/network")) yield return new VMwareNetwork(vmware, obj); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/VMware/VMwareResourcePool.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using Newtonsoft.Json.Linq; 17 | 18 | namespace MaxRunSoftware.Utilities.External; 19 | 20 | public class VMwareResourcePool : VMwareObject 21 | { 22 | public string Name { get; } 23 | public string ResourcePool { get; } 24 | 25 | // ReSharper disable once UnusedParameter.Local 26 | public VMwareResourcePool(VMwareClient vmware, JToken obj) 27 | { 28 | Name = obj.ToString("name"); 29 | ResourcePool = obj.ToString("resource_pool"); 30 | } 31 | 32 | public static IEnumerable Query(VMwareClient vmware) 33 | { 34 | foreach (var obj in vmware.GetValueArray("/rest/vcenter/resource-pool")) yield return new VMwareResourcePool(vmware, obj); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/VMware/VMwareStoragePolicy.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using System.Linq; 17 | using Newtonsoft.Json.Linq; 18 | 19 | namespace MaxRunSoftware.Utilities.External; 20 | 21 | public class VMwareStoragePolicy : VMwareObject 22 | { 23 | public class Disk : VMwareObject 24 | { 25 | public string Key { get; } 26 | public string VmHome { get; } 27 | public IReadOnlyList Disks { get; } 28 | 29 | public Disk(JToken obj) 30 | { 31 | Key = obj.ToString("key"); 32 | VmHome = obj.ToString("value", "vm_home"); 33 | Disks = obj["value"]?["disks"].OrEmpty().Select(o => o?.ToString()).WhereNotNull().ToList(); 34 | } 35 | } 36 | 37 | public string Name { get; } 38 | public string Description { get; } 39 | public string Policy { get; } 40 | public IReadOnlyList Disks { get; } 41 | 42 | public VMwareStoragePolicy(VMwareClient vmware, JToken obj) 43 | { 44 | Name = obj.ToString("name"); 45 | Description = obj.ToString("description"); 46 | Policy = obj.ToString("policy"); 47 | 48 | Disks = vmware.GetValueArray($"/rest/vcenter/storage/policies/{Policy}/vm").OrEmpty().Select(o => new Disk(o)).ToList(); 49 | } 50 | 51 | public static IEnumerable Query(VMwareClient vmware) 52 | { 53 | foreach (var obj in vmware.GetValueArray("/rest/vcenter/storage/policies")) yield return new VMwareStoragePolicy(vmware, obj); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/Version.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.External; 16 | 17 | public static class Version 18 | { 19 | public static string Value => Utilities.Version.Value; 20 | } 21 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/WebBrowser/WebBrowserType.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.External; 16 | 17 | public enum WebBrowserType 18 | { 19 | Chrome, 20 | Edge, 21 | Firefox, 22 | InternetExplorer, 23 | Opera 24 | } 25 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.External/WindowsTaskScheduler/WindowsTaskSchedulerExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using Microsoft.Win32.TaskScheduler; 17 | 18 | namespace MaxRunSoftware.Utilities.External; 19 | 20 | public static class WindowsTaskSchedulerExtensions 21 | { 22 | public static WindowsTaskSchedulerPath GetPath(this Task task) => new(task); 23 | 24 | public static WindowsTaskSchedulerPath GetPath(this TaskFolder folder) => new(folder); 25 | 26 | public static DaysOfTheWeek ToDaysOfTheWeek(this DayOfWeek dayOfWeek) => 27 | dayOfWeek switch 28 | { 29 | DayOfWeek.Sunday => DaysOfTheWeek.Sunday, 30 | DayOfWeek.Monday => DaysOfTheWeek.Monday, 31 | DayOfWeek.Tuesday => DaysOfTheWeek.Tuesday, 32 | DayOfWeek.Wednesday => DaysOfTheWeek.Wednesday, 33 | DayOfWeek.Thursday => DaysOfTheWeek.Thursday, 34 | DayOfWeek.Friday => DaysOfTheWeek.Friday, 35 | DayOfWeek.Saturday => DaysOfTheWeek.Saturday, 36 | _ => throw new ArgumentOutOfRangeException(nameof(dayOfWeek), dayOfWeek, null) 37 | }; 38 | } 39 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/AtomicBooleanTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // ReSharper disable ConditionIsAlwaysTrueOrFalse 16 | 17 | namespace MaxRunSoftware.Utilities.Tests; 18 | 19 | public class AtomicBooleanTests 20 | { 21 | [Fact] 22 | public void EqualsWork() 23 | { 24 | var ab1 = new AtomicBoolean(true); 25 | var ab2 = new AtomicBoolean(false); 26 | 27 | var b1 = true; 28 | var b2 = false; 29 | 30 | Assert.True(ab1.Equals(b1)); 31 | Assert.True(ab2.Equals(b2)); 32 | Assert.True(b1.Equals(ab1)); 33 | Assert.True(b2.Equals(ab2)); 34 | Assert.True(ab1.Equals(new AtomicBoolean(true))); 35 | 36 | Assert.False(ab1.Equals(b2)); 37 | Assert.False(ab2.Equals(b1)); 38 | Assert.False(b1.Equals(ab2)); 39 | Assert.False(b2.Equals(ab1)); 40 | Assert.False(ab1.Equals(ab2)); 41 | Assert.False(ab2.Equals(ab1)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/BucketTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // ReSharper disable RedundantAssignment 16 | 17 | namespace MaxRunSoftware.Utilities.Tests; 18 | 19 | public class BucketReadOnlyTests 20 | { 21 | [Fact] 22 | public void Testing() 23 | { 24 | var cgf = new CacheGenFunc(); 25 | 26 | var bro = new BucketCache(cgf.GenVal); 27 | Assert.Equal(0, cgf.TimesCalled); 28 | Assert.Empty(bro.Keys); 29 | 30 | var val = bro["a"]; 31 | Assert.Equal("Va", val); 32 | Assert.Equal(1, cgf.TimesCalled); 33 | Assert.Single(bro.Keys); 34 | 35 | val = bro["a"]; 36 | Assert.Equal("Va", val); 37 | Assert.Equal(1, cgf.TimesCalled); 38 | Assert.Single(bro.Keys); 39 | 40 | val = bro["b"]; 41 | Assert.Equal("Vb", val); 42 | Assert.Equal(2, cgf.TimesCalled); 43 | Assert.Equal(2, bro.Keys.Count()); 44 | 45 | val = bro["a"]; 46 | Assert.Equal("Va", val); 47 | Assert.Equal(2, cgf.TimesCalled); 48 | Assert.Equal(2, bro.Keys.Count()); 49 | 50 | val = bro["n"]; 51 | Assert.Null(val); 52 | Assert.Equal(3, cgf.TimesCalled); 53 | Assert.Equal(3, bro.Keys.Count()); 54 | 55 | val = bro["n"]; 56 | Assert.Null(val); 57 | Assert.Equal(3, cgf.TimesCalled); 58 | Assert.Equal(3, bro.Keys.Count()); 59 | 60 | try 61 | { 62 | val = bro[null]; 63 | Assert.True(false, "Expecting exception to be thrown"); 64 | } 65 | catch (Exception) { Assert.True(true); } 66 | } 67 | 68 | private class CacheGenFunc 69 | { 70 | public int TimesCalled { get; private set; } 71 | 72 | public string GenVal(string key) 73 | { 74 | TimesCalled++; 75 | if (key == "n") return null; 76 | 77 | return "V" + key; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/Config.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // ReSharper disable InconsistentNaming 16 | 17 | namespace MaxRunSoftware.Utilities.Tests; 18 | 19 | public static class Config 20 | { 21 | public static string Sql_MsSql_ConnectionString => "Server=172.16.46.3;Database=NorthWind;User Id=testuser;Password=testpass;TrustServerCertificate=True;"; 22 | 23 | public static string Sql_MySql_ConnectionString => "Server=172.16.46.3;Database=NorthWind;User Id=testuser;Password=testpass;"; 24 | 25 | //public static string Sql_Oracle_ConnectionString => "Data Source=172.16.46.9;User Id=system;Password=oracle;"; 26 | public static string Sql_Oracle_ConnectionString => "Data Source=172.16.46.9:1521/orcl;User Id=testuser;Password=testpass;"; 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/MaxRunSoftware.Utilities.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | false 6 | 1.13.1 7 | 8 | 9 | 10 | 11 | 12 | runtime; build; native; contentfiles; analyzers; buildtransitive 13 | all 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/MaxRunSoftware.Utilities.Tests.csproj.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/Threading/ExecutablePoolTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Tests; 16 | 17 | public class ExecutablePoolTests 18 | { 19 | public class Executable : IExecutable 20 | { 21 | public int ExecutedCount { get; private set; } 22 | 23 | public void Execute() 24 | { 25 | Thread.Sleep(10); 26 | ExecutedCount++; 27 | 28 | } 29 | } 30 | 31 | public class OnComplete 32 | { 33 | public int CompletedCount { get; private set; } 34 | public void Complete(ExecutablePool pool) => CompletedCount++; 35 | 36 | } 37 | 38 | [Fact] 39 | public void AllTasksExecuted() 40 | { 41 | var list = new List(); 42 | var executableCount = 1000; 43 | for (var i = 0; i < executableCount; i++) list.Add(new Executable()); 44 | 45 | var oc = new OnComplete(); 46 | 47 | 48 | 49 | var c = new ExecutablePoolConfig 50 | { 51 | Enumerator = list.GetEnumerator(), 52 | NumberOfThreads = 12, 53 | OnComplete = oc.Complete, 54 | }; 55 | 56 | using (var ep = ExecutablePool.Execute(c)) 57 | { 58 | while (!ep.GetState(false).IsComplete) 59 | { 60 | Thread.Sleep(100); 61 | } 62 | 63 | var state = ep.GetState(true); 64 | Assert.True(state.ExecutingItems.IsEmpty()); 65 | Assert.True(state.ThreadsActive == 0); 66 | Assert.True(state.ThreadsInactive == 12); 67 | Assert.True(state.ThreadsTotal == 12); 68 | } 69 | 70 | 71 | Assert.True(list.All(o => o.ExecutedCount == 1)); 72 | Assert.True(oc.CompletedCount == 1); 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/Threading/SingleUseTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities.Tests; 16 | 17 | public class SingleUseTests 18 | { 19 | [Fact] 20 | public void SingleThreaded() 21 | { 22 | var su = new SingleUse(); 23 | Assert.False(su.IsUsed); 24 | 25 | Assert.True(su.TryUse()); 26 | Assert.True(su.IsUsed); 27 | Assert.False(su.TryUse()); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | global using Xunit; 16 | global using System; 17 | global using System.Collections.Generic; 18 | global using System.Linq; 19 | global using System.Threading; 20 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/BucketCache.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | /// 18 | /// Non-thread safe cache implementation using backing dictionary and value generation function 19 | /// 20 | /// Key 21 | /// Generated Value 22 | public class BucketCache : IBucketReadOnly 23 | { 24 | private readonly IDictionary dictionary; 25 | private readonly Func factory; 26 | 27 | public BucketCache(Func factory, IDictionary dictionary) 28 | { 29 | this.factory = factory.CheckNotNull(nameof(factory)); 30 | this.dictionary = dictionary.CheckNotNull(nameof(dictionary)); 31 | } 32 | 33 | public BucketCache(Func factory) : this(factory, new Dictionary()) { } 34 | 35 | public IEnumerable Keys => dictionary.Keys; 36 | 37 | public TValue this[TKey key] 38 | { 39 | get 40 | { 41 | if (!dictionary.TryGetValue(key, out var value)) dictionary[key] = value = factory(key); 42 | 43 | return value; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/BucketCacheThreadSafe.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | /// 18 | /// Thread safe cache implementation using backing dictionary and value generation function. 19 | /// 20 | /// Key 21 | /// Generated Value 22 | public class BucketCacheThreadSafe : IBucketReadOnly 23 | { 24 | private readonly IDictionary dictionary; 25 | private readonly Func factory; 26 | private readonly object locker = new(); 27 | 28 | public BucketCacheThreadSafe(Func factory, IDictionary dictionary) 29 | { 30 | this.factory = factory.CheckNotNull(nameof(factory)); 31 | this.dictionary = dictionary.CheckNotNull(nameof(dictionary)); 32 | } 33 | 34 | public BucketCacheThreadSafe(Func factory) : this(factory, new Dictionary()) { } 35 | 36 | public IEnumerable Keys 37 | { 38 | get 39 | { 40 | lock (locker) { return dictionary.Keys; } 41 | } 42 | } 43 | 44 | public TValue this[TKey key] 45 | { 46 | get 47 | { 48 | lock (locker) 49 | { 50 | if (!dictionary.TryGetValue(key, out var value)) 51 | { 52 | value = factory(key); 53 | dictionary.Add(key, value); 54 | } 55 | 56 | return value; 57 | } 58 | } 59 | } 60 | 61 | public void Clear() 62 | { 63 | lock (locker) { dictionary.Clear(); } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/BucketExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public static class BucketExtensions 18 | { 19 | public static IBucket AsBucket(this IDictionary dictionary) => new BucketDictionaryWrapper(dictionary); 20 | 21 | public static IEnumerable<(TKey key, TValue value)> GetItems(this IBucketReadOnly bucket) => bucket.Keys.Select(key => (key, bucket[key])); 22 | 23 | private sealed class BucketDictionaryWrapper : IBucket 24 | { 25 | private readonly IDictionary dictionary; 26 | 27 | public BucketDictionaryWrapper(IDictionary dictionary) { this.dictionary = dictionary; } 28 | 29 | public TValue this[TKey key] 30 | { 31 | get => dictionary[key]; 32 | set => dictionary[key] = value; 33 | } 34 | 35 | TValue IBucketReadOnly.this[TKey key] => dictionary[key]; 36 | 37 | public IEnumerable Keys => dictionary.Keys; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/BucketStoreBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public abstract class BucketStoreBase : IBucketStore 18 | { 19 | public IBucket this[string name] => new Bucket(this, name.CheckNotNullTrimmed(nameof(name))); 20 | 21 | protected virtual string CleanName(string name) => name.CheckNotNullTrimmed(nameof(name)); 22 | 23 | protected virtual TKey CleanKey(TKey key) => key; 24 | 25 | protected virtual TValue CleanValue(TValue value) => value; 26 | 27 | protected abstract TValue GetValue(string bucketName, TKey bucketKey); 28 | 29 | protected abstract IEnumerable GetKeys(string bucketName); 30 | 31 | protected abstract void SetValue(string bucketName, TKey bucketKey, TValue bucketValue); 32 | 33 | private sealed class Bucket : IBucket 34 | { 35 | private readonly string bucketName; 36 | private readonly BucketStoreBase bucketStore; 37 | 38 | public Bucket(BucketStoreBase bucketStore, string bucketName) 39 | { 40 | this.bucketStore = bucketStore.CheckNotNull(nameof(bucketStore)); 41 | this.bucketName = bucketName.CheckNotNullTrimmed(nameof(bucketName)); 42 | } 43 | 44 | public IEnumerable Keys => 45 | bucketStore.GetKeys(bucketStore.CleanName(bucketName)) ?? Enumerable.Empty(); 46 | 47 | public TTValue this[TTKey key] 48 | { 49 | get => bucketStore.CleanValue(bucketStore.GetValue(bucketStore.CleanName(bucketName), 50 | bucketStore.CleanKey(key))); 51 | set => bucketStore.SetValue(bucketStore.CleanName(bucketName), bucketStore.CleanKey(key), 52 | bucketStore.CleanValue(value)); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/BucketStoreMemory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public class BucketStoreMemory : BucketStoreBase 18 | { 19 | private static readonly Func> dictionaryFactoryDefault = () => new Dictionary(); 20 | 21 | private readonly Dictionary> buckets = new(StringComparer.OrdinalIgnoreCase); 22 | private readonly Func> dictionaryFactory; 23 | private readonly TValue nullValue; 24 | 25 | public BucketStoreMemory(TValue nullValue = default, Func> dictionaryFactory = null) 26 | { 27 | this.nullValue = nullValue; 28 | this.dictionaryFactory = dictionaryFactory ?? dictionaryFactoryDefault; 29 | } 30 | 31 | public IEnumerable Buckets 32 | { 33 | get 34 | { 35 | lock (buckets) { return buckets.Keys.ToList(); } 36 | } 37 | } 38 | 39 | protected override IEnumerable GetKeys(string bucketName) 40 | { 41 | IDictionary d; 42 | lock (buckets) 43 | { 44 | if (!buckets.TryGetValue(bucketName, out d)) return new TKey[] { }; 45 | } 46 | 47 | lock (d) { return d.Keys.ToArray(); } 48 | } 49 | 50 | protected override TValue GetValue(string bucketName, TKey bucketKey) 51 | { 52 | IDictionary d; 53 | lock (buckets) 54 | { 55 | if (!buckets.TryGetValue(bucketName, out d)) return nullValue; 56 | } 57 | 58 | lock (d) { return d.TryGetValue(bucketKey, out var val) ? val : nullValue; } 59 | } 60 | 61 | protected override void SetValue(string bucketName, TKey bucketKey, TValue bucketValue) 62 | { 63 | IDictionary d; 64 | lock (buckets) 65 | { 66 | if (!buckets.TryGetValue(bucketName, out d)) 67 | { 68 | if (bucketValue == null) return; 69 | 70 | buckets.Add(bucketName, d = dictionaryFactory()); 71 | } 72 | } 73 | 74 | lock (d) 75 | { 76 | if (bucketValue == null) { d.Remove(bucketKey); } 77 | else { d[bucketKey] = bucketValue; } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/BucketStoreMemoryString.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public class BucketStoreMemoryString : BucketStoreMemory 18 | { 19 | private static readonly Func> dictionaryFactoryDefault = () => new Dictionary(StringComparer.OrdinalIgnoreCase); 20 | 21 | public BucketStoreMemoryString() : base(dictionaryFactory: dictionaryFactoryDefault) { } 22 | 23 | protected override string CleanName(string name) => base.CleanName(name).CheckNotNullTrimmed(nameof(name)); 24 | 25 | protected override string CleanKey(string key) => base.CleanKey(key).CheckNotNullTrimmed(nameof(key)); 26 | 27 | protected override string CleanValue(string value) => base.CleanValue(value).TrimOrNull(); 28 | } 29 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/IBucket.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | /// 18 | /// Read-Write Key+Value store 19 | /// 20 | /// Key type 21 | /// Value type 22 | public interface IBucket : IBucketReadOnly 23 | { 24 | /// 25 | /// Get or sets a value for a specific key 26 | /// 27 | /// Key 28 | /// Value 29 | new TValue this[TKey key] { get; set; } 30 | } 31 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/IBucketReadOnly.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | /// 18 | /// Readonly Key+Value store 19 | /// 20 | /// Key type 21 | /// Value type 22 | public interface IBucketReadOnly 23 | { 24 | /// 25 | /// Keys in bucket 26 | /// 27 | IEnumerable Keys { get; } 28 | 29 | /// 30 | /// Gets value for a specific key 31 | /// 32 | /// Key 33 | /// Value 34 | TValue this[TKey key] { get; } 35 | } 36 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Buckets/IBucketStore.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | /// 18 | /// Storage for multiple buckets based on a name 19 | /// 20 | /// Key type 21 | /// Value type 22 | public interface IBucketStore 23 | { 24 | IBucket this[string name] { get; } 25 | } 26 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Collections/ComparatorBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | /// 18 | /// Makes implementing a comparator easier 19 | /// 20 | /// Type this comparator compares 21 | public abstract class ComparatorBase : IComparer, IEqualityComparer, IComparer, IEqualityComparer 22 | { 23 | public abstract int Compare(T x, T y); 24 | 25 | public abstract int GetHashCode(T obj); 26 | 27 | public int Compare(object x, object y) 28 | { 29 | if (x == y) return 0; 30 | 31 | if (x == null) return -1; 32 | 33 | if (y == null) return 1; 34 | 35 | if (x is T sa) 36 | { 37 | if (y is T sb) { return Compare(sa, sb); } 38 | } 39 | 40 | if (x is IComparable ia) return ia.CompareTo(y); 41 | 42 | throw new ArgumentException("Argument_ImplementIComparable"); // TODO: Better error 43 | } 44 | 45 | public virtual bool Equals(T x, T y) => Compare(x, y) == 0; 46 | 47 | public new bool Equals(object x, object y) 48 | { 49 | if (x == y) return true; 50 | 51 | if (x == null || y == null) return false; 52 | 53 | if (x is T sa) 54 | { 55 | if (y is T sb) { return Equals(sa, sb); } 56 | } 57 | 58 | return x.Equals(y); 59 | } 60 | 61 | public int GetHashCode(object obj) 62 | { 63 | obj.CheckNotNull(nameof(obj)); 64 | 65 | if (obj is T s) return GetHashCode(s); 66 | 67 | return obj.GetHashCode(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Data/TableRow.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public sealed class TableRow : IReadOnlyList, IBucketReadOnly, IBucketReadOnly 18 | { 19 | private readonly string[] data; 20 | public Table Table { get; } 21 | public int RowIndex { get; } 22 | 23 | internal TableRow(Table table, string[] data, int rowIndex) 24 | { 25 | Table = table; 26 | this.data = data; 27 | RowIndex = rowIndex; 28 | } 29 | 30 | public int GetNumberOfCharacters(int lengthOfNull) => data.GetNumberOfCharacters(lengthOfNull); 31 | 32 | #region IBucketReadOnly 33 | 34 | public IEnumerable Keys => Table.Columns.ColumnNames; 35 | IEnumerable IBucketReadOnly.Keys => Keys; 36 | 37 | public string this[string columnName] => this[Table.Columns[columnName].Index]; 38 | 39 | #endregion IBucketReadOnly 40 | 41 | #region IBucketReadOnly 42 | 43 | IEnumerable IBucketReadOnly.Keys => Table.Columns; 44 | public string this[TableColumn column] => this[column.Index]; 45 | 46 | #endregion IBucketReadOnly 47 | 48 | #region IReadOnlyList 49 | 50 | public int Count => Table.Columns.Count; 51 | public string this[int columnIndex] => data[columnIndex]; 52 | 53 | public IEnumerator GetEnumerator() => ((IEnumerable)data).GetEnumerator(); 54 | 55 | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); 56 | 57 | #endregion IReadOnlyList 58 | 59 | public string[] ToArray() => data.Copy(); 60 | } 61 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Data/XmlElement.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public class XmlElement 18 | { 19 | public string Name { get; set; } 20 | public string Value { get; set; } 21 | public IDictionary Attributes { get; } = new Dictionary(); 22 | public IList Children { get; } = new List(); 23 | 24 | public IEnumerable ChildrenAll 25 | { 26 | get 27 | { 28 | foreach (var child in Children) 29 | { 30 | yield return child; 31 | foreach (var child2 in child.ChildrenAll) yield return child2; 32 | } 33 | } 34 | } 35 | 36 | public XmlElement Parent { get; set; } 37 | 38 | public string this[string attributeName] => Attributes.GetValueCaseInsensitive(attributeName); 39 | } 40 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Data/XmlReader.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Xml; 16 | 17 | namespace MaxRunSoftware.Utilities; 18 | 19 | public class XmlReader 20 | { 21 | public static XmlElement Read(string xml) 22 | { 23 | var document = new XmlDocument(); 24 | document.LoadXml(xml); 25 | return Process(document); 26 | } 27 | 28 | private static XmlElement Process(XmlDocument document) 29 | { 30 | var elementRoot = document.DocumentElement; 31 | return ProcessElement(elementRoot, null); 32 | } 33 | 34 | private static XmlElement ProcessElement(System.Xml.XmlElement element, XmlElement parent) 35 | { 36 | var newElement = new XmlElement(); 37 | newElement.Name = element.Name; 38 | newElement.Parent = parent; 39 | var attrs = element.Attributes; 40 | foreach (XmlAttribute attr in attrs) newElement.Attributes[attr.Name] = attr.Value; 41 | 42 | var values = new List(); 43 | foreach (XmlNode child in element.ChildNodes) 44 | { 45 | if (child.NodeType.In(XmlNodeType.Element)) 46 | { 47 | var childElement = (System.Xml.XmlElement)child; 48 | var newChild = ProcessElement(childElement, newElement); 49 | newElement.Children.Add(newChild); 50 | } 51 | else if (child.NodeType.In(XmlNodeType.Text)) 52 | { 53 | var v = child.Value; 54 | if (v != null) values.Add(v); 55 | } 56 | } 57 | 58 | if (values.IsNotEmpty()) newElement.Value = values.ToStringDelimited(""); 59 | 60 | 61 | return newElement; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Extensions/ExtensionsIO.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public static class ExtensionsIO 18 | { 19 | public static string[] RemoveBase(this FileSystemInfo info, DirectoryInfo baseToRemove, bool caseSensitive = false) 20 | { 21 | var sourceParts = info.FullName.Split('/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Where(o => o.TrimOrNull() != null).ToArray(); 22 | var baseParts = baseToRemove.FullName.Split('/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Where(o => o.TrimOrNull() != null).ToArray(); 23 | 24 | var msgInvalidParent = $"{nameof(baseToRemove)} of {baseToRemove.FullName} is not a parent directory of {info.FullName}"; 25 | 26 | if (baseParts.Length > sourceParts.Length) throw new ArgumentException(msgInvalidParent, nameof(baseToRemove)); 27 | 28 | var list = new List(); 29 | for (var i = 0; i < sourceParts.Length; i++) 30 | { 31 | if (i >= baseParts.Length) { list.Add(sourceParts[i]); } 32 | else 33 | { 34 | if (caseSensitive) 35 | { 36 | if (!string.Equals(sourceParts[i], baseParts[i])) throw new ArgumentException(msgInvalidParent, nameof(baseToRemove)); 37 | } 38 | else 39 | { 40 | if (!string.Equals(sourceParts[i], baseParts[i], StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(msgInvalidParent, nameof(baseToRemove)); 41 | } 42 | } 43 | } 44 | 45 | return list.ToArray(); 46 | } 47 | 48 | public static long GetLength(this FileInfo file) 49 | { 50 | if (file == null) return -1; 51 | 52 | // https://stackoverflow.com/a/26473940 53 | if (file.Attributes.HasFlag(FileAttributes.ReparsePoint)) // probably symbolic link 54 | // https://stackoverflow.com/a/57454136 55 | { 56 | using (Stream fs = Util.FileOpenRead(file.FullName)) { return fs.Length; } 57 | } 58 | 59 | return file.Length; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Extensions/ExtensionsReflection.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Diagnostics; 16 | 17 | namespace MaxRunSoftware.Utilities; 18 | 19 | public static class ExtensionsReflection 20 | { 21 | public static string GetFileVersion(this Assembly assembly) => FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; 22 | 23 | public static string GetVersion(this Assembly assembly) => assembly.GetCustomAttribute()?.Version; 24 | } 25 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Logging/ILogAppender.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public interface ILogAppender 18 | { 19 | LogLevel Level { get; } 20 | 21 | // ReSharper disable once UnusedParameter.Global 22 | void Log(object sender, LogEventArgs args); 23 | } 24 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Logging/ILogFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public interface ILogFactory : IDisposable 18 | { 19 | bool IsTraceEnabled { get; } 20 | 21 | bool IsDebugEnabled { get; } 22 | 23 | bool IsInfoEnabled { get; } 24 | 25 | bool IsWarnEnabled { get; } 26 | 27 | bool IsErrorEnabled { get; } 28 | 29 | bool IsCriticalEnabled { get; } 30 | 31 | //event EventHandler Logging; 32 | 33 | ILogger GetLogger(); 34 | 35 | ILogger GetLogger(Type type); 36 | 37 | void AddAppender(ILogAppender appender); 38 | } 39 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Logging/ILogger.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public interface ILogger 18 | { 19 | void Trace(string message); 20 | 21 | void Trace(Exception exception); 22 | 23 | void Trace(string message, Exception exception); 24 | 25 | void Debug(string message); 26 | 27 | void Debug(Exception exception); 28 | 29 | void Debug(string message, Exception exception); 30 | 31 | void Info(string message); 32 | 33 | void Info(Exception exception); 34 | 35 | void Info(string message, Exception exception); 36 | 37 | void Warn(string message); 38 | 39 | void Warn(Exception exception); 40 | 41 | void Warn(string message, Exception exception); 42 | 43 | void Error(string message); 44 | 45 | void Error(Exception exception); 46 | 47 | void Error(string message, Exception exception); 48 | 49 | void Critical(string message); 50 | 51 | void Critical(Exception exception); 52 | 53 | void Critical(string message, Exception exception); 54 | } 55 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Logging/LogLevel.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public enum LogLevel : byte 18 | { 19 | Trace = 0, 20 | Debug = 1, 21 | Info = 2, 22 | Warn = 3, 23 | Error = 4, 24 | Critical = 5 25 | } 26 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/MaxRunSoftware.Utilities.csproj.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True 4 | True 5 | True 6 | True 7 | True 8 | True 9 | True 10 | True 11 | True 12 | True 13 | True -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Reflection/TypeConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public delegate object TypeConverter(object inputObject, Type outputType); 18 | 19 | public static class TypeConverterExtensions 20 | { 21 | public static TypeConverter AsTypeConverter(this Converter converter) => (inputObject, _) => converter((TInput)inputObject); 22 | 23 | public static Converter AsConverter(this TypeConverter typeConverter) => inputObject => (TOutput)typeConverter(inputObject, typeof(TOutput)); 24 | } 25 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Sql/SqlExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public static class SqlExtensions 18 | { 19 | public static IDataReader ExecuteReaderExceptionWrapped(this IDbCommand command, bool exceptionShowFullSql) 20 | { 21 | try { return command.ExecuteReader(); } 22 | catch (Exception e) { throw new SqlException(e, command, exceptionShowFullSql); } 23 | } 24 | 25 | public static object ExecuteScalarExceptionWrapped(this IDbCommand command, bool exceptionShowFullSql) 26 | { 27 | try { return command.ExecuteScalar(); } 28 | catch (Exception e) { throw new SqlException(e, command, exceptionShowFullSql); } 29 | } 30 | 31 | public static int ExecuteNonQueryExceptionWrapped(this IDbCommand command, bool exceptionShowFullSql) 32 | { 33 | try { return command.ExecuteNonQuery(); } 34 | catch (Exception e) { throw new SqlException(e, command, exceptionShowFullSql); } 35 | } 36 | 37 | public static List ExecuteQueryToList(this Sql sql, string sqlQuery, params SqlParameter[] parameters) 38 | { 39 | var list = new List(); 40 | var table = ExecuteQueryToTable(sql, sqlQuery, parameters); 41 | if (table == null) return list; 42 | if (table.Columns.Count < 1) return list; 43 | 44 | foreach (var row in table) list.Add(row[0]); 45 | 46 | return list; 47 | } 48 | 49 | public static Table ExecuteQueryToTable(this Sql sql, string sqlQuery, params SqlParameter[] parameters) => ExecuteQueryToTables(sql, sqlQuery, parameters).FirstOrDefault(); 50 | 51 | public static Table[] ExecuteQueryToTables(this Sql sql, string sqlQuery, params SqlParameter[] parameters) => Table.Create(sql.ExecuteQuery(sqlQuery, parameters)); 52 | } 53 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Sql/SqlParameter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | /// 18 | /// Parameter used for calling SQL stored procedure and functions 19 | /// 20 | public sealed class SqlParameter 21 | { 22 | /// 23 | /// Parameter name 24 | /// 25 | public string Name { get; } 26 | 27 | /// 28 | /// Parameter type 29 | /// 30 | public DbType Type { get; } 31 | 32 | /// 33 | /// Parameter value 34 | /// 35 | public object Value { get; } 36 | 37 | /// 38 | /// Constructs a new SqlParameter attempting to figure out the Type based on the value supplied 39 | /// 40 | /// Name 41 | /// Value 42 | public SqlParameter(string name, object value) 43 | { 44 | Name = name; 45 | 46 | if (value == null) 47 | { 48 | Type = DbType.String; 49 | Value = null; 50 | } 51 | else 52 | { 53 | if (Constant.TYPE_DBTYPE.TryGetValue(value.GetType(), out var dbType)) 54 | { 55 | Type = dbType; 56 | Value = value; 57 | } 58 | else 59 | { 60 | Type = DbType.String; 61 | Value = value.ToStringGuessFormat(); 62 | } 63 | } 64 | } 65 | 66 | /// 67 | /// Constructs a new SqlParameter 68 | /// 69 | /// Name 70 | /// Value 71 | /// 72 | public SqlParameter(string name, object value, DbType type) 73 | { 74 | Name = name; 75 | Value = value; 76 | Type = type; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Sql/SqlTypeAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | [AttributeUsage(AttributeTargets.Field)] 18 | public class SqlTypeAttribute : Attribute 19 | { 20 | public DbType DbType { get; } 21 | public Type DotNetType { get; set; } 22 | 23 | public string SqlTypeNames { get; set; } 24 | public object ActualSqlType { get; set; } 25 | 26 | public SqlTypeAttribute(DbType dbType) { DbType = dbType; } 27 | } 28 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Threading/ConsumerProducerThread.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Concurrent; 16 | 17 | namespace MaxRunSoftware.Utilities; 18 | 19 | /// 20 | /// Thread that consumes an object and produces a new object 21 | /// 22 | /// Consumed Type 23 | /// Produced Type 24 | public class ConsumerProducerThread : ConsumerProducerThreadBase 25 | { 26 | private readonly Func func; 27 | 28 | public ConsumerProducerThread(BlockingCollection consumerQueue, BlockingCollection producerQueue, Func func) : base(consumerQueue, producerQueue) { this.func = func.CheckNotNull(nameof(func)); } 29 | 30 | protected override TProduce WorkConsumeProduce(TConsume item) => func(item); 31 | } 32 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Threading/ConsumerProducerThreadBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Concurrent; 16 | using System.Threading; 17 | 18 | namespace MaxRunSoftware.Utilities; 19 | 20 | public abstract class ConsumerProducerThreadBase : ConsumerThreadBase 21 | { 22 | // ReSharper disable once StaticMemberInGenericType 23 | private static readonly ILogger log = LogFactory.GetLogger(MethodBase.GetCurrentMethod()!.DeclaringType); 24 | 25 | private readonly BlockingCollection producerQueue; 26 | private readonly CancellationTokenSource cancellation = new(); 27 | 28 | protected ConsumerProducerThreadBase(BlockingCollection consumerQueue, BlockingCollection producerQueue) : base(consumerQueue) { this.producerQueue = producerQueue.CheckNotNull(nameof(producerQueue)); } 29 | 30 | protected override void WorkConsume(TConsume item) 31 | { 32 | if (IsCancelled) return; 33 | 34 | try 35 | { 36 | var produceItem = WorkConsumeProduce(item); 37 | if (IsCancelled) return; 38 | 39 | producerQueue.Add(produceItem, cancellation.Token); 40 | } 41 | catch (OperationCanceledException) { Cancel(); } 42 | } 43 | 44 | protected override void CancelInternal() 45 | { 46 | try { cancellation.Cancel(); } 47 | catch (Exception e) { log.Warn("CancellationTokenSource.Cancel() request threw exception", e); } 48 | 49 | base.CancelInternal(); 50 | } 51 | 52 | protected abstract TProduce WorkConsumeProduce(TConsume item); 53 | } 54 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Threading/ConsumerThread.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Concurrent; 16 | 17 | namespace MaxRunSoftware.Utilities; 18 | 19 | /// 20 | /// Thread for performing a specified action on a collection 21 | /// 22 | /// The Type of object to process 23 | public class ConsumerThread : ConsumerThreadBase 24 | { 25 | private readonly Action action; 26 | 27 | public ConsumerThread(BlockingCollection queue, Action action) : base(queue) { this.action = action.CheckNotNull(nameof(action)); } 28 | 29 | protected override void WorkConsume(T item) => action(item); 30 | } 31 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Threading/ConsumerThreadState.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public enum ConsumerThreadState 18 | { 19 | Waiting, 20 | Working, 21 | Stopped 22 | } 23 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Threading/IntervalThread.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Threading; 16 | 17 | namespace MaxRunSoftware.Utilities; 18 | 19 | /// 20 | /// Simple polling thread that calls WorkInterval() periodically 21 | /// 22 | public abstract class IntervalThread : ThreadBase 23 | { 24 | private DateTime lastCheck; 25 | public TimeSpan SleepInterval { get; set; } = TimeSpan.FromSeconds(1); 26 | public TimeSpan SleepIntervalDelay { get; set; } = TimeSpan.FromMilliseconds(50); 27 | 28 | protected override void Work() 29 | { 30 | while (true) 31 | { 32 | if (IsDisposed) return; 33 | 34 | if (DateTime.UtcNow - lastCheck > SleepInterval) 35 | { 36 | WorkInterval(); 37 | lastCheck = DateTime.UtcNow; 38 | } 39 | 40 | Thread.Sleep(SleepIntervalDelay); 41 | } 42 | } 43 | 44 | protected abstract void WorkInterval(); 45 | } 46 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Threading/MutexLockTimeoutException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Threading; 16 | 17 | namespace MaxRunSoftware.Utilities; 18 | 19 | public sealed class MutexLockTimeoutException : WaitHandleCannotBeOpenedException 20 | { 21 | public string MutexName { get; } 22 | public TimeSpan Timeout { get; } 23 | 24 | public MutexLockTimeoutException(string mutexName, TimeSpan timeout) : base("Failed to acquire mutex [" + mutexName + "] after waiting " + timeout.ToStringTotalSeconds(3) + "s") 25 | { 26 | MutexName = mutexName; 27 | Timeout = timeout; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Threading/SingleUse.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public class SingleUse 18 | { 19 | private readonly AtomicBoolean boolean = false; 20 | 21 | public bool IsUsed => boolean; 22 | 23 | /// 24 | /// Attempts to 'use' this instance. If this is the first time using it, we will return 25 | /// true. Otherwise we return false if we have already been used. 26 | /// 27 | /// true if we have never used before, false if we have already been used 28 | public bool TryUse() => boolean.SetTrue(); 29 | } 30 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Usings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | global using System; 16 | global using System.Collections; 17 | global using System.Collections.Generic; 18 | global using System.Data; 19 | global using System.IO; 20 | global using System.Linq; 21 | global using System.Reflection; 22 | global using System.Text; 23 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Utils/UtilBaseConversion.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public static partial class Util 18 | { 19 | #region Base16 20 | 21 | private static readonly uint[] lookupBase16 = Base16(); 22 | 23 | private static uint[] Base16() 24 | { 25 | var result = new uint[256]; 26 | for (var i = 0; i < 256; i++) 27 | { 28 | var s = i.ToString("X2"); 29 | result[i] = s[0] + ((uint)s[1] << 16); 30 | } 31 | 32 | return result; 33 | } 34 | 35 | public static string Base16(byte[] bytes) 36 | { 37 | // https://stackoverflow.com/a/24343727/48700 https://stackoverflow.com/a/624379 38 | 39 | var lookup32 = lookupBase16; 40 | var result = new char[bytes.Length * 2]; 41 | for (var i = 0; i < bytes.Length; i++) 42 | { 43 | var val = lookup32[bytes[i]]; 44 | result[2 * i] = (char)val; 45 | result[2 * i + 1] = (char)(val >> 16); 46 | } 47 | 48 | return new string(result); 49 | } 50 | 51 | public static byte[] Base16(string base16String) 52 | { 53 | var numberChars = base16String.Length; 54 | var bytes = new byte[numberChars / 2]; 55 | for (var i = 0; i < numberChars; i += 2) bytes[i / 2] = Convert.ToByte(base16String.Substring(i, 2), 16); 56 | 57 | return bytes; 58 | } 59 | 60 | #endregion Base16 61 | 62 | #region Base64 63 | 64 | public static string Base64(byte[] bytes) => Convert.ToBase64String(bytes); 65 | 66 | public static byte[] Base64(string base64String) => Convert.FromBase64String(base64String); 67 | 68 | #endregion Base64 69 | } 70 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Utils/UtilChangeType.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Net; 16 | using System.Net.Mail; 17 | 18 | namespace MaxRunSoftware.Utilities; 19 | 20 | public static partial class Util 21 | { 22 | public static TOutput ChangeType(TInput obj) => (TOutput)ChangeType(obj, typeof(TOutput)); 23 | 24 | public static TOutput ChangeType(object obj) => (TOutput)ChangeType(obj, typeof(TOutput)); 25 | 26 | public static object ChangeType(object obj, Type outputType) 27 | { 28 | if (obj == null || obj == DBNull.Value) 29 | { 30 | if (!outputType.IsValueType) return null; 31 | 32 | if (outputType.IsNullable()) return null; 33 | 34 | return Convert.ChangeType(obj, outputType); // Should throw exception 35 | } 36 | 37 | if (outputType.IsNullable(out var underlyingTypeOutput)) return ChangeType(obj, underlyingTypeOutput); 38 | 39 | var inputType = obj.GetType(); 40 | if (inputType.IsNullable(out var underlyingTypeInput)) inputType = underlyingTypeInput; 41 | 42 | if (inputType == typeof(string)) 43 | { 44 | var o = obj as string; 45 | if (outputType == typeof(bool)) return o.ToBool(); 46 | 47 | if (outputType == typeof(DateTime)) return o.ToDateTime(); 48 | 49 | if (outputType == typeof(Guid)) return o.ToGuid(); 50 | 51 | if (outputType == typeof(MailAddress)) return o.ToMailAddress(); 52 | 53 | if (outputType == typeof(Uri)) return o.ToUri(); 54 | 55 | if (outputType == typeof(IPAddress)) return o.ToIPAddress(); 56 | 57 | if (outputType.IsEnum) return outputType.GetEnumValue(o); 58 | } 59 | 60 | if (inputType.IsEnum) return ChangeType(obj.ToString(), outputType); 61 | 62 | if (outputType == typeof(string)) return obj.ToStringGuessFormat(); 63 | 64 | return Convert.ChangeType(obj, outputType); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Utils/UtilConsole.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public static partial class Util 18 | { 19 | private readonly struct ConsoleColorChanger : IDisposable 20 | { 21 | private readonly ConsoleColor foreground; 22 | private readonly bool foregroundSwitched; 23 | private readonly ConsoleColor background; 24 | private readonly bool backgroundSwitched; 25 | 26 | public ConsoleColorChanger(ConsoleColor? foreground, ConsoleColor? background) 27 | { 28 | this.foreground = Console.ForegroundColor; 29 | this.background = Console.BackgroundColor; 30 | 31 | var foregroundSwitch = false; 32 | if (foreground != null) 33 | { 34 | if (this.foreground != foreground.Value) 35 | { 36 | foregroundSwitch = true; 37 | Console.ForegroundColor = foreground.Value; 38 | } 39 | } 40 | 41 | foregroundSwitched = foregroundSwitch; 42 | 43 | var backgroundSwitch = false; 44 | if (background != null) 45 | { 46 | if (this.background != background.Value) 47 | { 48 | backgroundSwitch = true; 49 | Console.BackgroundColor = background.Value; 50 | } 51 | } 52 | 53 | backgroundSwitched = backgroundSwitch; 54 | } 55 | 56 | public void Dispose() 57 | { 58 | if (foregroundSwitched) Console.ForegroundColor = foreground; 59 | 60 | if (backgroundSwitched) Console.BackgroundColor = background; 61 | } 62 | } 63 | 64 | /// 65 | /// Changes the console color, and then changes it back when it is disposed 66 | /// 67 | /// The foreground color 68 | /// The background color 69 | /// A disposable that will change the colors back once disposed 70 | public static IDisposable ChangeConsoleColor(ConsoleColor? foreground = null, ConsoleColor? background = null) => new ConsoleColorChanger(foreground, background); 71 | } 72 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Utils/UtilEnum.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public static partial class Util 18 | { 19 | public static IReadOnlyList GetEnumValues() where TEnum : struct, Enum => (TEnum[])Enum.GetValues(typeof(TEnum)); 20 | 21 | public static TEnum CombineEnumFlags(IEnumerable enums) where TEnum : struct, Enum => (TEnum)Enum.Parse(typeof(TEnum), string.Join(", ", enums.Select(o => o.ToString()))); 22 | } 23 | -------------------------------------------------------------------------------- /MaxRunSoftware.Utilities/Version.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2022 Max Run Software (dev@maxrunsoftware.com) 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace MaxRunSoftware.Utilities; 16 | 17 | public static class Version 18 | { 19 | public static string Value => "1.13.1"; 20 | } 21 | -------------------------------------------------------------------------------- /test.bat: -------------------------------------------------------------------------------- 1 | SETLOCAL 2 | SET host=localhost 3 | SET username=testadmin 4 | SET password=mySecretAdmin1 5 | 6 | huc ActiveDirectoryAddUser -h=%host% -u=%username% -p=%password% -fn=Test1 -ln=Doe -dn="John1 Doe" -ea="jd1@aol.com" jd1 7 | ::huc ActiveDirectoryDisableUsers -h=%host% -u=%username% -p=%password% -l=5 8 | huc ActiveDirectoryDisableUser -h=%host% -u=%username% -p=%password% jd1 9 | huc ActiveDirectoryListObjectDetails -h=%host% -u=%username% -p=%password% Administrator 10 | 11 | huc ActiveDirectoryChangePassword -h=%host% -u=%username% -p=%password% jd1 myNew29Password 12 | huc ActiveDirectoryAddGroup -h=%host% -u=%username% -p=%password% TestGroup1 13 | huc ActiveDirectoryAddOU -h=%host% -u=%username% -p=%password% OU1 14 | huc ActiveDirectoryAddOU -h=%host% -u=%username% -p=%password% -pou=OU1 OU2 15 | huc ActiveDirectoryMoveGroup -h=%host% -u=%username% -p=%password% TestGroup1 OU1 16 | huc ActiveDirectoryMoveUser -h=%host% -u=%username% -p=%password% jd1 OU2 17 | huc ActiveDirectoryAddUserToGroup -h=%host% -u=%username% -p=%password% jd1 TestGroup1 18 | 19 | huc ActiveDirectoryListUsers -h=%host% -u=%username% -p=%password% j?1 20 | huc ActiveDirectoryListGroups -h=%host% -u=%username% -p=%password% Test*1 21 | 22 | huc ActiveDirectoryRemoveUserFromGroup -h=%host% -u=%username% -p=%password% jd1 TestGroup1 23 | huc ActiveDirectoryRemoveUser -h=%host% -u=%username% -p=%password% jd1 24 | huc ActiveDirectoryRemoveGroup -h=%host% -u=%username% -p=%password% TestGroup1 25 | huc ActiveDirectoryRemoveOU -h=%host% -u=%username% -p=%password% OU2 26 | huc ActiveDirectoryRemoveOU -h=%host% -u=%username% -p=%password% OU1 27 | 28 | huc WindowsTaskSchedulerAdd -h=%host% -u=%username% -p=%password% -tn=MyTask1 -tu=System -td="Some task description" -t1="DAILY 11:42" -t2="HOURLY 25" C:\Temp\SomeTestFile.bat 29 | huc WindowsTaskSchedulerAdd -h=%host% -u=%username% -p=%password% -tn=/MyTasks/MyTask2 -tu=System -td="Some task description 2" -t1="DAILY 9:18" -t2="HOURLY 12" C:\Temp\SomeTestFile.bat 30 | 31 | huc WindowsTaskSchedulerRemove -h=%host% -u=%username% -p=%password% MyTask1 32 | huc WindowsTaskSchedulerRemove -h=%host% -u=%username% -p=%password% /MyTasks/MyTask2 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /toolbox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxrunsoftware/huc/35d4f91a2503005c5946fa805079a436534c6f04/toolbox.png --------------------------------------------------------------------------------