diff --git a/App.config b/App.config new file mode 100644 index 0000000..193aecc --- /dev/null +++ b/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/App.xaml b/App.xaml new file mode 100644 index 0000000..7996407 --- /dev/null +++ b/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/App.xaml.cs b/App.xaml.cs new file mode 100644 index 0000000..5192f68 --- /dev/null +++ b/App.xaml.cs @@ -0,0 +1,11 @@ +using System.Windows; + +namespace GetWMIBasic +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..40f9bad --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,54 @@ +# Community Guidelines + +At TheFlightSims, we recognize and celebrate the creativity and collaboration of open +source contributors and the diversity of skills, experiences, cultures, and +opinions they bring to the projects and communities they participate in. + +Every one of the communities is an inclusive environment, based on treating +all individuals respectfully, regardless of +gender identity and expression, sexual orientation, and disabilities, +neurodiversity, physical appearance, body size, ethnicity, nationality, race, +age, religion, or similar personal characteristics. + +We value diverse opinions, but we value respectful behavior more. + +Respectful behavior includes: + +* Being considerate, kind, constructive, and helpful. +* Not engaging in demeaning, discriminatory, harassing, hateful, sexualized, or + physically threatening behavior, speech, and imagery. +* Not engaging in unwanted physical contact. + +Some of TheFlightSims' open-source projects may adopt an explicit project code of +conduct, which may have additional detailed expectations for participants. Most +of those projects will use our modified Contributor Covenant. + +## Resolve peacefully + +We do not believe that all conflict is necessarily bad; healthy debate and +disagreement often yield positive results. However, it is never okay to be +disrespectful. + +If you see someone behaving disrespectfully, you are encouraged to address the +behavior directly with those involved. Many issues can be resolved quickly and +easily, and this gives people more control over the outcome of their disputes. +If you are unable to resolve the matter for any reason, or if the behavior is +threatening or harassing, report it. We are dedicated to providing an +environment where participants feel welcome and safe. + +## Reporting problems + +Some of TheFlightSims' open-source projects may adopt a project-specific code of conduct. +In those cases, a TheFlightSims employee will be identified as the Project Steward, +who will receive and handle reports of code of conduct violations. If a project hasn’t identified a Project Steward, you can report problems by +emailing mailto:report_concern@theflightsims.com + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is +taken. The identity of the reporter will be omitted from the details of the +report supplied to the accused. In potentially harmful situations, such as +ongoing harassment or threats to anyone's safety, we may take action without +notice. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..2ba4ad5 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,24 @@ +# Contributing + +## Environment requirements + +### Git repo + +To clone the repo, run, use this command + +```bash +git clone https://github.com/tfslabs/get-wmi-basic.git +``` + +### Build with Visual Studio (only for Windows) + +To contribute, you may need Visual Studio 2022. Required Visual Studio 2022 SDKs: + +* .NET 4.8 SDK and targeting pack +* Windows 10 SDK (10.0.18362.0) (if applicable) + +## Build from source + +You can open the `Get WMI Basic.csproj` to open the project in Visual Studio + +However, since this project is a part of [Windows Server Management Tool](https://github.com/TheFlightSims/windowsserver-mgmttools), you may need to clone the whole repo, before using Visual Studio, because the full Visual Studio Solution are already configured with valid build configurations. diff --git a/ConnectForm.xaml b/ConnectForm.xaml new file mode 100644 index 0000000..cb70948 --- /dev/null +++ b/ConnectForm.xaml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ConnectForm.xaml.cs b/ConnectForm.xaml.cs new file mode 100644 index 0000000..dafdbca --- /dev/null +++ b/ConnectForm.xaml.cs @@ -0,0 +1,71 @@ +using System.Security; +using System.Windows; + +namespace GetWMIBasic +{ + public partial class ConnectForm : Window + { + /* + * Global properties + */ + private bool isConnectLocally; + + public ConnectForm() + { + isConnectLocally = false; + InitializeComponent(); + } + + /* + * Button-based methods + */ + + private void ConnetToExternal_Button(object sender, RoutedEventArgs e) + { + if ( + ComputerName_TextBox.Text.Length == 0 || + UserName_TextBox.Text.Length == 0 || + Password_TextBox.Password.Length == 0) + { + MessageBox.Show("Please don't leave anything empty", "Error", MessageBoxButton.OK, MessageBoxImage.Warning); + } + else + { + DialogResult = true; + } + } + + private void ConnectToLocal_Button(object sender, RoutedEventArgs e) + { + isConnectLocally = true; + DialogResult = true; + } + + private void Cancel_Button(object sender, RoutedEventArgs e) + { + Close(); + } + + /* + * Non-button methods + */ + public (string, string, SecureString) ReturnValue() + { + ShowDialog(); + + string computerName = (isConnectLocally) ? "localhost" : ComputerName_TextBox.Text; + string userName = (isConnectLocally) ? "" : UserName_TextBox.Text; + SecureString password = new SecureString(); + + if (!isConnectLocally) + { + foreach (char c in Password_TextBox.Password) + { + password.AppendChar(c); + } + } + + return (computerName, userName, password); + } + } +} diff --git a/Get WMI Basic.csproj b/Get WMI Basic.csproj new file mode 100644 index 0000000..bb5bc06 --- /dev/null +++ b/Get WMI Basic.csproj @@ -0,0 +1,164 @@ + + + + + Debug + AnyCPU + {FCCF35F0-772A-46F6-8F73-28EAD514F36E} + WinExe + GetWMIBasic + GetWMIBasic + v4.8 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + true + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + 7.3 + prompt + true + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + 7.3 + prompt + true + true + + + true + bin\x86\Debug\ + DEBUG;TRACE + full + x86 + 7.3 + prompt + true + + + bin\x86\Release\ + TRACE + true + pdbonly + x86 + 7.3 + prompt + true + true + + + + app.manifest + + + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + + Designer + MSBuild:Compile + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + ConnectForm.xaml + + + MainWindow.xaml + Code + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + False + Microsoft .NET Framework 4.8 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 + false + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE index fdddb29..8015f5d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,24 +1,10 @@ -This is free and unencumbered software released into the public domain. +TheFlightSims OSS License -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. +Copyright 2025 TheFlightSims -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. +Get WMI Basic -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software—including without limitation to use, copy, modify, merge, publish, distribute, and sublicense copies of the Software—subject to the following conditions: -For more information, please refer to +1. You must include this full license text in all copies or substantial portions of the Software. +2. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. diff --git a/MainWindow.xaml b/MainWindow.xaml new file mode 100644 index 0000000..238a08c --- /dev/null +++ b/MainWindow.xaml @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Welcome + + + + diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs new file mode 100644 index 0000000..4d0f7fe --- /dev/null +++ b/MainWindow.xaml.cs @@ -0,0 +1,229 @@ +using System; +using System.Linq; +using System.Management; +using System.Runtime.InteropServices; +using System.Security; +using System.Threading.Tasks; +using System.Windows; + +using GetWMIBasic.WMIMethods; + +namespace GetWMIBasic +{ + public partial class MainWindow : Window + { + /* + * Global properties + */ + protected MachineMethods machine; + + public MainWindow() + { + InitializeComponent(); + machine = new MachineMethods(); + Loaded += MainWindow_Loaded; + } + + private async void MainWindow_Loaded(object sender, RoutedEventArgs e) + { + await Refresh(); + } + + /* + * Button-based methods + */ + private async void ConnectToAnotherComputer_Button(object sender, RoutedEventArgs e) + { + ConnectForm connectForm = new ConnectForm(); + + (string computerName, string username, SecureString password) userCredential = connectForm.ReturnValue(); + + if (userCredential.computerName != "") + { + machine = null; + if (!userCredential.computerName.Equals("localhost")) + { + machine = new MachineMethods(userCredential); + } + else + { + machine = new MachineMethods(); + } + + await Refresh(); + } + } + + private void Exit_Button(object sender, RoutedEventArgs e) + { + Application.Current.Shutdown(); + } + + private async void Restart_Button(object sender, RoutedEventArgs e) + { + if (MessageBox.Show($"Do you want to restart the computer {machine.GetComputerName()}?", "Proceed?", MessageBoxButton.YesNo) == MessageBoxResult.Yes) + { + StatusBarChange("Loading", true); + + try + { + if (machine.GetComputerName() == "localhost") + { + throw new ManagementException("Local Host cannot be restarted"); + } + + machine.Connect("root\\cimv2"); + await machine.CallMethod("Win32_OperatingSystem", "*", "Win32Shutdown", new object[] { 6 }); + } + catch (UnauthorizedAccessException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to catch the Authenticate with {machine.GetComputerName()}: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + catch (COMException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to reach {machine.GetComputerName()}: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + + catch (ManagementException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to catch the Management Method: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + finally + { + StatusBarChange("Done", false); + } + } + } + + private async void Shutdown_Button(object sender, RoutedEventArgs e) + { + if (MessageBox.Show($"Do you want to shutdown the computer {machine.GetComputerName()}?", "Proceed?", MessageBoxButton.YesNo) == MessageBoxResult.Yes) + { + StatusBarChange("Loading", true); + + try + { + if (machine.GetComputerName() == "localhost") + { + throw new ManagementException("Local Host cannot be shut down"); + } + + machine.Connect("root\\cimv2"); + await machine.CallMethod("Win32_OperatingSystem", "*", "Win32Shutdown", new object[] { 5 }); + } + catch (UnauthorizedAccessException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to catch the Authenticate with {machine.GetComputerName()}: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + catch (COMException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to reach {machine.GetComputerName()}: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + + catch (ManagementException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to catch the Management Method: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + finally + { + StatusBarChange("Done", false); + } + } + } + + private async void Refresh_Button(object sender, RoutedEventArgs e) + { + await Refresh(); + } + + /* + * Non-button methods + */ + private async Task Refresh() + { + StatusBarChange("Loading", true); + + try + { + machine.Connect("root\\cimv2"); + + var biosProperties = machine.GetObjects("Win32_BIOS", "*"); + foreach (ManagementObject biosProperty in (await biosProperties).Cast()) + { + BIOS_Manufacturer.Text = biosProperty["Manufacturer"]?.ToString() ?? string.Empty; + BIOS_Name.Text = biosProperty["Name"]?.ToString() ?? string.Empty; + BIOS_SN.Text = biosProperty["SerialNumber"]?.ToString() ?? string.Empty; + BIOS_Version.Text = biosProperty["Version"]?.ToString() ?? string.Empty; + } + + var osProperties = machine.GetObjects("Win32_ComputerSystem", "*"); + foreach (ManagementObject osProperty in (await osProperties).Cast()) + { + Computer_Name.Text = osProperty["Name"]?.ToString() ?? string.Empty; + Computer_Domain.Text = osProperty["Domain"]?.ToString() ?? string.Empty; + Computer_Memory.Text = osProperty["TotalPhysicalMemory"]?.ToString() ?? string.Empty; + Computer_SysType.Text = osProperty["SystemType"]?.ToString() ?? string.Empty; + } + } + catch (UnauthorizedAccessException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to catch the Authenticate with {machine.GetComputerName()}: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + catch (COMException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to reach {machine.GetComputerName()}: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + + catch (ManagementException ex) + { +#if DEBUG + MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#else + MessageBox.Show($"Failed to catch the Management Method: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); +#endif + } + finally + { + StatusBarChange("Done", false); + } + } + + protected void StatusBarChange(string label, bool progressbarLoading) + { + Bottom_Label.Text = label; + Bottom_ProgressBar.IsIndeterminate = progressbarLoading; + } + } +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e829148 --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,50 @@ +using System.Reflection; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("GetWMIBasic")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("GetWMIBasic")] +[assembly: AssemblyCopyright("Copyright © 2025")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Properties/Resources.Designer.cs b/Properties/Resources.Designer.cs new file mode 100644 index 0000000..1de4cce --- /dev/null +++ b/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace GetWMIBasic.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GetWMIBasic.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Properties/Resources.resx b/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Properties/Settings.Designer.cs b/Properties/Settings.Designer.cs new file mode 100644 index 0000000..e3cba28 --- /dev/null +++ b/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace GetWMIBasic.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Properties/Settings.settings b/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 2a126a2..c0f985e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,25 @@ -# get-wmi-basic -Get Basic Information of a Remote Computer using WMI +# Get WMI Basics + +Get basic information about a remote computer using WMI. + +This project also serves as a template for other WMI projects or for Windows client and server management tools. + +## Prerequisites + +See in [CONTRIBUTING.md](CONTRIBUTING.md) + +## Getting started (Usage) + +This template includes a minimal usage example that demonstrates how to connect via WMI. + +### Included files + +* `WMIMethods/MachineMethods.cs` — Class that encapsulates operations for the target computer (the WMI target). It contains methods for querying and invoking WMI operations and includes getters/setters and basic interfaces for WMI development. +* `MainWindow.*` — Main window (graphical user interface). +* `ConnectForm.*` — Authentication form where the user enters credentials. + +## Suggestions / To do + +* Add build instructions (how to compile) and a short usage example showing how to run the application. +* Add the target .NET / C# framework version. +* Add a license file if you intend to publish this repository. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..0786ed8 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,28 @@ +# Security + +TheFlightSims takes the security responsibilities of our software products and services seriously, including all open-source software and closed-source software + +## Reporting Security Issues + +**Note:** You shouldn't report the security vulnerabilities on the Issue or the public place. Any attackers can use these vulnerabilities to exploit non-public data - which causes security vulnerability. + +You can report security issues on these platforms: + +* The repository security page (Preferred) +* [Email](mailto:report_concern@theflightsims.com) + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + +* Type of issue (e.g., buffer overflow, SQL injection, cross-site scripting) +* Full paths of the source file(s) related to the manifestation of the issue +* The location of the affected source code (tag/branch/commit or direct URL) +* Any special configuration required to reproduce the issue +* Step-by-step instructions to reproduce the issue +* Proof-of-concept or exploit code (if possible) +* Impact of the case, including how an attacker might control the issue + +This information will help us triage your report more quickly. + +## Preferred Languages + +You can use all human-valid languages. However, you may consider using English (US) to prevent misunderstanding. diff --git a/WMIMethods/MachineMethods.cs b/WMIMethods/MachineMethods.cs new file mode 100644 index 0000000..038f336 --- /dev/null +++ b/WMIMethods/MachineMethods.cs @@ -0,0 +1,103 @@ +using System.Linq; +using System.Management; +using System.Security; +using System.Threading.Tasks; + +namespace GetWMIBasic.WMIMethods +{ + public class MachineMethods + { + /* + * Class properties + */ + + protected (string computerName, string username, SecureString password) userCredential; + protected ConnectionOptions credential; + protected ManagementScope scope; + protected ManagementObjectSearcher searcher; + + protected string scopePath; + protected bool isLocal; + + /* + * Machine Method + * 1. Empty - Local + * 2. Or Connect through WMI + */ + + public MachineMethods() + { + userCredential.computerName = "localhost"; + isLocal = true; + credential = new ConnectionOptions + { + Impersonation = ImpersonationLevel.Impersonate, + Authentication = AuthenticationLevel.PacketPrivacy, + EnablePrivileges = true + }; + } + + public MachineMethods((string computerName, string username, SecureString password) userCredential) + { + this.userCredential.computerName = userCredential.computerName; + this.userCredential.username = userCredential.username; + this.userCredential.password = userCredential.password; + isLocal = false; + credential = new ConnectionOptions + { + Username = userCredential.username, + SecurePassword = userCredential.password, + Impersonation = ImpersonationLevel.Impersonate, + Authentication = AuthenticationLevel.PacketPrivacy, + EnablePrivileges = true + }; + } + + /* + * Get value + */ + public string GetComputerName() + { + return userCredential.computerName; + } + + /* + * Connection method + */ + + public void Connect(string nameSpace) + { + scopePath = $"\\\\{userCredential.computerName}\\{nameSpace}"; + scope = (isLocal) ? new ManagementScope(scopePath) : new ManagementScope(scopePath, credential); + scope.Connect(); + } + + /* + * Get WMI objects + */ + public async Task GetObjects(string className, string fields) + { + ObjectQuery query = new ObjectQuery($"SELECT {fields} FROM {className}"); + searcher = new ManagementObjectSearcher(scope, query); + return await Task.Run(() => searcher?.Get()); + } + + /* + * Call WMI Method + */ + public async Task CallMethod(string className, string fields, string methodName, object[] args) + { + ObjectQuery query = new ObjectQuery($"SELECT {fields} FROM {className}"); + await Task.Run(() => + { + using (var searcher = new ManagementObjectSearcher(scope, query)) + { + foreach (ManagementObject manageObject in searcher.Get().Cast()) + { + manageObject.InvokeMethod(methodName, args); + } + } + }); + } + } +} diff --git a/app.manifest b/app.manifest new file mode 100644 index 0000000..d9f9518 --- /dev/null +++ b/app.manifest @@ -0,0 +1,24 @@ + + + + + + true + + + + + + + + + + + + + + + \ No newline at end of file