├── RunAsAdmin
├── Resources
│ ├── imageres_78.ico
│ ├── imageres_105.ico
│ ├── imageres_106.ico
│ └── imageres_107.ico
├── Properties
│ ├── Settings.settings
│ ├── Settings.Designer.cs
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Views
│ ├── SplashScreenWindow.xaml.cs
│ ├── SplashScreenWindow.xaml
│ ├── UpdateWindow.xaml
│ ├── SettingsWindow.xaml
│ ├── LogViewerWindow.xaml
│ ├── UpdateWindow.xaml.cs
│ ├── MainWindow.xaml
│ ├── SettingsWindow.xaml.cs
│ ├── LogViewerWindow.xaml.cs
│ └── MainWindow.xaml.cs
├── App.xaml
├── Core
│ ├── DomainHelper.cs
│ ├── WM.cs
│ ├── FileHelper.cs
│ ├── UserListHelper.cs
│ ├── DirectoryHelper.cs
│ ├── SecurityHelper.cs
│ └── Helper.cs
├── app.config
├── RunAsAdmin.csproj
├── App.xaml.cs
└── GlobalVars.cs
├── .github
├── ISSUE_TEMPLATE
│ └── bug_report.md
├── workflows
│ ├── ci.yml
│ └── release.yml
└── scripts
│ └── check-version.ps1
├── RunAsAdmin.sln
├── .gitattributes
├── README.md
├── .gitignore
└── LICENSE
/RunAsAdmin/Resources/imageres_78.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HendrikKoelbel/RunAsAdmin/HEAD/RunAsAdmin/Resources/imageres_78.ico
--------------------------------------------------------------------------------
/RunAsAdmin/Resources/imageres_105.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HendrikKoelbel/RunAsAdmin/HEAD/RunAsAdmin/Resources/imageres_105.ico
--------------------------------------------------------------------------------
/RunAsAdmin/Resources/imageres_106.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HendrikKoelbel/RunAsAdmin/HEAD/RunAsAdmin/Resources/imageres_106.ico
--------------------------------------------------------------------------------
/RunAsAdmin/Resources/imageres_107.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HendrikKoelbel/RunAsAdmin/HEAD/RunAsAdmin/Resources/imageres_107.ico
--------------------------------------------------------------------------------
/RunAsAdmin/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/SplashScreenWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using MahApps.Metro.Controls;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using System.Threading;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Shapes;
14 |
15 | namespace RunAsAdmin.Views
16 | {
17 | ///
18 | /// Interaktionslogik für SplashScreenWindow.xaml
19 | ///
20 | public partial class SplashScreenWindow : MetroWindow
21 | {
22 | public SplashScreenWindow()
23 | {
24 | InitializeComponent();
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: HendrikKoelbel
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | > Errors are visible in the LogViewer. (to open it just right-click on the main window)
21 |
22 | **Expected behavior**
23 | A clear and concise description of what you expected to happen.
24 |
25 | **Screenshots**
26 | If applicable, add screenshots to help explain your problem.
27 |
28 | **Informations**
29 | - OS: [e.g. Windows]
30 | - OS Version: [e.g. 10]
31 | - Program Version [e.g. v2.0.0]
32 |
33 | **Additional context**
34 | Add any other context about the problem here.
35 |
--------------------------------------------------------------------------------
/RunAsAdmin/App.xaml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/SplashScreenWindow.xaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/RunAsAdmin/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // Dieser Code wurde von einem Tool generiert.
4 | // Laufzeitversion:4.0.30319.42000
5 | //
6 | // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
7 | // der Code erneut generiert wird.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace RunAsAdmin.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/RunAsAdmin.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.4.33403.182
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RunAsAdmin", "RunAsAdmin\RunAsAdmin.csproj", "{CA48B25B-3826-4ACA-9D1C-908A64122301}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{AFBAC3CF-927E-4860-89EC-9B4353607C46}"
9 | ProjectSection(SolutionItems) = preProject
10 | README.md = README.md
11 | RunAsAdmin.zip = RunAsAdmin.zip
12 | EndProjectSection
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {CA48B25B-3826-4ACA-9D1C-908A64122301}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {CA48B25B-3826-4ACA-9D1C-908A64122301}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {CA48B25B-3826-4ACA-9D1C-908A64122301}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {CA48B25B-3826-4ACA-9D1C-908A64122301}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {BC6D1632-D479-4E14-8A7B-67A747C53A58}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/UpdateWindow.xaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/RunAsAdmin/Core/DomainHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.DirectoryServices.ActiveDirectory;
4 |
5 | namespace RunAsAdmin.Core
6 | {
7 | public static class DomainHelper
8 | {
9 |
10 | ///
11 | /// Is a function which collects all domains or local PC names.
12 | ///
13 | /// A list with the local PC name and all connected domains.
14 | public static List GetAllDomains()
15 | {
16 | var domainList = new List();
17 | domainList.Add(Environment.MachineName);
18 | using (var forest = Forest.GetCurrentForest())
19 | {
20 | foreach (Domain domain in forest.Domains)
21 | {
22 | domainList.Add(domain.Name);
23 | domain.Dispose();
24 | }
25 | return domainList;
26 | }
27 | }
28 |
29 | ///
30 | /// Is a function which collects all domains.
31 | ///
32 | /// A list with all connected domains.
33 | public static List GetDomains()
34 | {
35 | var domainList = new List();
36 | using (var forest = Forest.GetCurrentForest())
37 | {
38 | foreach (Domain domain in forest.Domains)
39 | {
40 | domainList.Add(domain.Name);
41 | domain.Dispose();
42 | }
43 | return domainList;
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/SettingsWindow.xaml:
--------------------------------------------------------------------------------
1 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/RunAsAdmin/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/LogViewerWindow.xaml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/RunAsAdmin/Core/WM.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Win32;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.Drawing;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Runtime.InteropServices;
9 | using System.Security;
10 | using System.Security.AccessControl;
11 | using System.Security.Principal;
12 | using System.Threading;
13 | using System.Threading.Tasks;
14 | using System.Windows.Forms;
15 |
16 | namespace RunAsAdmin.Core
17 | {
18 | public static class WM
19 | {
20 | #region Window to front
21 | [DllImport("User32.dll")]
22 | public static extern int SetForegroundWindow(int hWnd);
23 | #endregion
24 |
25 | #region Placeholder
26 | private const int EM_SETCUEBANNER = 0x1501;
27 |
28 | [DllImport("user32.dll", CharSet = CharSet.Auto)]
29 | private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
30 |
31 | [DllImport("user32.dll")]
32 | private static extern bool GetComboBoxInfo(IntPtr hwnd, ref COMBOBOXINFO pcbi);
33 | [StructLayout(LayoutKind.Sequential)]
34 |
35 | private struct COMBOBOXINFO
36 | {
37 | public int cbSize;
38 | public RECT rcItem;
39 | public RECT rcButton;
40 | public UInt32 stateButton;
41 | public IntPtr hwndCombo;
42 | public IntPtr hwndItem;
43 | public IntPtr hwndList;
44 | }
45 |
46 | [StructLayout(LayoutKind.Sequential)]
47 | private struct RECT
48 | {
49 | public int left;
50 | public int top;
51 | public int right;
52 | public int bottom;
53 | }
54 |
55 | public static void Placeholder(Control control, string placeholder)
56 | {
57 | try
58 | {
59 | if (control is ComboBox)
60 | {
61 | COMBOBOXINFO info = GetComboBoxInfo(control);
62 | SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, placeholder);
63 | }
64 | else
65 | {
66 | SendMessage(control.Handle, EM_SETCUEBANNER, 0, placeholder);
67 | }
68 | }
69 | catch (Exception)
70 | {
71 |
72 | }
73 | }
74 |
75 | private static COMBOBOXINFO GetComboBoxInfo(Control control)
76 | {
77 | COMBOBOXINFO info = new COMBOBOXINFO();
78 | info.cbSize = Marshal.SizeOf(info);
79 | GetComboBoxInfo(control.Handle, ref info);
80 | return info;
81 | }
82 | #endregion
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/RunAsAdmin/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // Allgemeine Informationen über eine Assembly werden über die folgenden
8 | // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
9 | // die einer Assembly zugeordnet sind.
10 | [assembly: AssemblyTitle("RunAsAdmin")]
11 | [assembly: AssemblyDescription("A tool for running programs as an administrator.")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("Hendrik Kölbel")]
14 | [assembly: AssemblyProduct("RunAsAdmin")]
15 | [assembly: AssemblyCopyright("Copyright © 2020")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
20 | // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
21 | // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
22 | [assembly: ComVisible(false)]
23 |
24 | //Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie
25 | //ImCodeVerwendeteKultur in der .csproj-Datei
26 | //in einer fest. Wenn Sie in den Quelldateien beispielsweise Deutsch
27 | //(Deutschland) verwenden, legen Sie auf \"de-DE\" fest. Heben Sie dann die Auskommentierung
28 | //des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile,
29 | //sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt.
30 |
31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
32 |
33 |
34 | [assembly: ThemeInfo(
35 | ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher
36 | //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird,
37 | // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.)
38 | ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs
39 | //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird,
40 | // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.)
41 | )]
42 |
43 |
44 | // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
45 | //
46 | // Hauptversion
47 | // Nebenversion
48 | // Buildnummer
49 | // Revision
50 | //
51 | // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
52 | // indem Sie "*" wie unten gezeigt eingeben:
53 | // [assembly: AssemblyVersion("1.0.*")]
54 | [assembly: AssemblyVersion("2.1.4")]
55 | [assembly: AssemblyFileVersion("2.1.4")]
56 | [assembly: NeutralResourcesLanguage("en")]
57 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/UpdateWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using MahApps.Metro.Controls;
2 | using Onova;
3 | using Onova.Services;
4 | using System;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 |
9 | namespace RunAsAdmin.Views
10 | {
11 | ///
12 | /// Interaktionslogik für UpdateWindow.xaml
13 | ///
14 | public partial class UpdateWindow : MetroWindow
15 | {
16 | #region Private variables
17 | private readonly CancellationTokenSource UpdateCts = new CancellationTokenSource();
18 | private readonly UpdateManager Manager;
19 | #endregion
20 |
21 | #region Initialize UpdateWindow
22 | public UpdateWindow()
23 | {
24 | InitializeComponent();
25 | this.LabelPercentage.Content = "0%/100%";
26 | Manager = new UpdateManager(new GithubPackageResolver(GlobalVars.GitHubUsername, GlobalVars.GitHubProjectName, GlobalVars.GitHubAssetName), new ZipPackageExtractor());
27 | }
28 | public UpdateWindow(UpdateManager updateManager)
29 | {
30 | InitializeComponent();
31 | this.LabelPercentage.Content = "0%/100%";
32 | Manager = updateManager;
33 | }
34 | #endregion
35 |
36 | #region Run update
37 | private async void UpdateWindow_ContentRendered(object sender, EventArgs e)
38 | {
39 | try
40 | {
41 | using (var manager = Manager)
42 | {
43 | var updatesResult = await manager.CheckForUpdatesAsync(UpdateCts.Token);
44 | Progress progressIndicator = new Progress(ReportProgress);
45 |
46 | // Prepare an update by downloading and extracting the package
47 | // (supports progress reporting and cancellation)
48 | await manager.PrepareUpdateAsync(updatesResult.LastVersion, progressIndicator, UpdateCts.Token);
49 |
50 | // Launch an executable that will apply the update
51 | // (can be instructed to restart the application afterwards)
52 | manager.LaunchUpdater(updatesResult.LastVersion);
53 |
54 | // Terminate the running application so that the updater can overwrite files
55 | Environment.Exit(0);
56 | }
57 | }
58 | catch (TaskCanceledException)
59 | {
60 | if (UpdateCts.IsCancellationRequested)
61 | {
62 | this.Close();
63 | }
64 | }catch (Exception ex)
65 | {
66 | GlobalVars.Loggi.Error(ex, ex.Message);
67 | }
68 | }
69 | #endregion
70 |
71 | #region Progress reporter
72 | public void ReportProgress(double value)
73 | {
74 | //Update the UI to reflect the progress value that is passed back.
75 | this.ProgressBarUpdate.Value = value * 100;
76 | this.LabelPercentage.Content = $"{Convert.ToInt32(value * 100)}%/100%";
77 | }
78 | #endregion
79 |
80 | #region Button click event with cancellation
81 | private void ButtonCancel_Click(object sender, RoutedEventArgs e)
82 | {
83 | try
84 | {
85 | UpdateCts.Cancel();
86 | }
87 | catch (Exception)
88 | {
89 | GlobalVars.Loggi.Information("The update was cancelled.");
90 | }
91 | }
92 | #endregion
93 | }
94 | }
--------------------------------------------------------------------------------
/RunAsAdmin/RunAsAdmin.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0-windows
4 | WinExe
5 | latest
6 | false
7 | true
8 | true
9 | true
10 |
11 |
12 | true
13 | win-x64
14 | false
15 | true
16 | false
17 |
18 |
19 |
20 | Resources\imageres_78.ico
21 | RunAsAdmin.App
22 | OnBuildSuccess
23 | False
24 | Hendrik Kölbel
25 | RunAsAdmin
26 |
27 |
28 |
29 | 5.2.1
30 |
31 |
32 | 4.19.0
33 |
34 |
35 | 5.0.2
36 |
37 |
38 | 5.0.21
39 |
40 |
41 | 2.4.11
42 |
43 |
44 | 6.2.1
45 |
46 |
47 | 10.0.0
48 |
49 |
50 | 4.7.0
51 |
52 |
53 | 13.0.4
54 |
55 |
56 | 2.6.13
57 |
58 |
59 | 1.0.32
60 |
61 |
62 | 4.2.0
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 | 10.0.0
71 |
72 |
73 | 2.12.2
74 |
75 |
76 | 4.1.2
77 |
78 |
79 | 1.3.0.5
80 |
81 |
82 | all
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/RunAsAdmin/Core/FileHelper.cs:
--------------------------------------------------------------------------------
1 | using SimpleImpersonation;
2 | using System;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Runtime.Versioning;
6 | using System.Security.AccessControl;
7 | using System.Security.Principal;
8 | using System.Threading.Tasks;
9 |
10 | namespace RunAsAdmin.Core
11 | {
12 | public static class FileHelper
13 | {
14 | public static bool HasFileRights(string filePath, FileSystemRights fileRights, string winUserString = null, WindowsIdentity winUser = null)
15 | {
16 | try
17 | {
18 | var security = new DirectoryInfo(filePath).GetAccessControl();
19 | var rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));
20 |
21 | if (winUserString != null)
22 | {
23 | return rules.OfType().Any(r =>
24 | ((int)r.FileSystemRights & (int)fileRights) != 0 && r.IdentityReference.Value == winUserString);
25 | }
26 | else if (winUser != null)
27 | {
28 | return rules.OfType().Any(r =>
29 | ((int)r.FileSystemRights & (int)fileRights) != 0 && r.IdentityReference.Value == winUser.User.Value);
30 | }
31 | return false;
32 | }
33 | catch (Exception ex)
34 | {
35 | GlobalVars.Loggi.Error(ex, ex.Message);
36 | return false;
37 | }
38 | }
39 |
40 | // Adds an ACL entry on the specified file for the specified account.
41 | public static void AddFileSecurity(string filePath, string winUserString = null, WindowsIdentity winUser = null,
42 | FileSystemRights rights = FileSystemRights.FullControl, AccessControlType controlType = AccessControlType.Allow)
43 | {
44 | // Get a FileSecurity object that represents the
45 | // current security settings.
46 | FileSecurity fSecurity = new FileInfo(filePath).GetAccessControl();
47 | if (winUserString != null)
48 | {
49 | // Add the FileSystemAccessRule to the security settings.
50 | fSecurity.AddAccessRule(new FileSystemAccessRule(winUserString,
51 | rights, controlType));
52 | }
53 | else if (winUser != null)
54 | {
55 | // Add the FileSystemAccessRule to the security settings.
56 | fSecurity.AddAccessRule(new FileSystemAccessRule(winUser.User.Value,
57 | rights, controlType));
58 | }
59 | FileInfo file = new FileInfo(filePath);
60 | // Set the new access settings.
61 | file.SetAccessControl(fSecurity);
62 | }
63 |
64 | // Removes an ACL entry on the specified file for the specified account.
65 | public static void RemoveFileSecurity(string filePath, string winUserString = null, WindowsIdentity winUser = null,
66 | FileSystemRights rights = FileSystemRights.FullControl, AccessControlType controlType = AccessControlType.Allow)
67 | {
68 | // Get a FileSecurity object that represents the
69 | // current security settings.
70 | FileSecurity fSecurity = new FileInfo(filePath).GetAccessControl();
71 |
72 | if (winUserString != null)
73 | {
74 | // Remove the FileSystemAccessRule from the security settings.
75 | fSecurity.RemoveAccessRule(new FileSystemAccessRule(winUserString,
76 | rights, controlType));
77 | }
78 | else if (winUser != null)
79 | {
80 | // Remove the FileSystemAccessRule from the security settings.
81 | fSecurity.RemoveAccessRule(new FileSystemAccessRule(winUser.User.Value,
82 | rights, controlType));
83 | }
84 |
85 | FileInfo file = new FileInfo(filePath);
86 | // Set the new access settings.
87 | file.SetAccessControl(fSecurity);
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI Build
2 |
3 | on:
4 | push:
5 | branches:
6 | - develop
7 | - 'claude/**'
8 | pull_request:
9 | branches:
10 | - main
11 | - master
12 | - develop
13 |
14 | jobs:
15 | build:
16 | name: Build and Test
17 | runs-on: windows-latest
18 |
19 | steps:
20 | - name: Checkout Code
21 | uses: actions/checkout@v4
22 |
23 | - name: Setup .NET 8
24 | uses: actions/setup-dotnet@v4
25 | with:
26 | dotnet-version: '8.0.x'
27 |
28 | - name: Display Build Information
29 | shell: pwsh
30 | run: |
31 | Write-Host "========================================" -ForegroundColor Cyan
32 | Write-Host "Build Information" -ForegroundColor Cyan
33 | Write-Host "========================================" -ForegroundColor Cyan
34 | Write-Host "Repository: ${{ github.repository }}" -ForegroundColor Yellow
35 | Write-Host "Branch: ${{ github.ref_name }}" -ForegroundColor Yellow
36 | Write-Host "Commit: ${{ github.sha }}" -ForegroundColor Yellow
37 | Write-Host "Event: ${{ github.event_name }}" -ForegroundColor Yellow
38 | Write-Host ".NET Version: $(dotnet --version)" -ForegroundColor Yellow
39 | Write-Host "========================================" -ForegroundColor Cyan
40 |
41 | - name: Restore Dependencies
42 | run: dotnet restore RunAsAdmin/RunAsAdmin.csproj
43 |
44 | - name: Build Debug
45 | run: dotnet build RunAsAdmin/RunAsAdmin.csproj -c Debug --no-restore
46 |
47 | - name: Publish Release (Single-File)
48 | run: dotnet publish RunAsAdmin/RunAsAdmin.csproj -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true
49 |
50 | - name: Verify Build Artifacts
51 | shell: pwsh
52 | run: |
53 | Write-Host "Checking for build artifacts..." -ForegroundColor Yellow
54 |
55 | $debugExe = "RunAsAdmin\bin\Debug\net8.0-windows\win-x64\RunAsAdmin.exe"
56 | $publishExe = "RunAsAdmin\bin\Release\net8.0-windows\win-x64\publish\RunAsAdmin.exe"
57 |
58 | if (Test-Path $debugExe) {
59 | $debugSize = (Get-Item $debugExe).Length
60 | $debugSizeMB = [math]::Round($debugSize / 1MB, 2)
61 | Write-Host " ✓ Debug build successful: $debugExe ($debugSizeMB MB)" -ForegroundColor Green
62 | } else {
63 | Write-Host " ✗ Debug build failed: $debugExe not found" -ForegroundColor Red
64 | exit 1
65 | }
66 |
67 | if (Test-Path $publishExe) {
68 | $releaseSize = (Get-Item $publishExe).Length
69 | $releaseSizeMB = [math]::Round($releaseSize / 1MB, 2)
70 | Write-Host " ✓ Release single-file publish successful: $publishExe ($releaseSizeMB MB)" -ForegroundColor Green
71 |
72 | # Check if any DLLs were created (should not be present for single-file)
73 | $publishDir = "RunAsAdmin\bin\Release\net8.0-windows\win-x64\publish"
74 | $dllCount = (Get-ChildItem $publishDir -Filter "*.dll" -ErrorAction SilentlyContinue | Measure-Object).Count
75 | if ($dllCount -eq 0) {
76 | Write-Host " ✓ Single-file packaging verified (no DLLs)" -ForegroundColor Green
77 | } else {
78 | Write-Host " ⚠ Warning: Found $dllCount DLL(s) in publish directory" -ForegroundColor Yellow
79 | }
80 | } else {
81 | Write-Host " ✗ Release publish failed: $publishExe not found" -ForegroundColor Red
82 | exit 1
83 | }
84 |
85 | - name: Upload Build Artifacts
86 | if: success()
87 | uses: actions/upload-artifact@v4
88 | with:
89 | name: build-artifacts
90 | path: |
91 | RunAsAdmin/bin/Release/net8.0-windows/win-x64/publish/RunAsAdmin.exe
92 | retention-days: 7
93 | if-no-files-found: warn
94 |
95 | - name: Build Summary
96 | if: always()
97 | shell: pwsh
98 | run: |
99 | Write-Host ""
100 | Write-Host "========================================" -ForegroundColor Cyan
101 | Write-Host "Build Summary" -ForegroundColor Cyan
102 | Write-Host "========================================" -ForegroundColor Cyan
103 |
104 | if ($LASTEXITCODE -eq 0) {
105 | Write-Host "✓ CI Build completed successfully" -ForegroundColor Green
106 | } else {
107 | Write-Host "✗ CI Build failed" -ForegroundColor Red
108 | }
109 |
110 | Write-Host "========================================" -ForegroundColor Cyan
111 |
--------------------------------------------------------------------------------
/RunAsAdmin/Core/UserListHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.DirectoryServices;
4 | using System.DirectoryServices.AccountManagement;
5 | using System.DirectoryServices.ActiveDirectory;
6 |
7 | namespace RunAsAdmin.Core
8 | {
9 | public static class UserListHelper
10 | {
11 | public static List GetADUsers()
12 | {
13 | var ADUsers = new List();
14 | try
15 | {
16 | using var forest = Forest.GetCurrentForest();
17 | foreach (Domain domain in forest.Domains)
18 | {
19 | using (var context = new PrincipalContext(ContextType.Domain, domain.Name))
20 | {
21 | using var searcher = new PrincipalSearcher(new UserPrincipal(context));
22 | foreach (var result in searcher.FindAll())
23 | {
24 | using (result)
25 | {
26 | DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
27 | if (de?.Properties["samAccountName"]?.Value != null)
28 | {
29 | ADUsers.Add(de.Properties["samAccountName"].Value.ToString());
30 | }
31 | }
32 | }
33 | }
34 | domain.Dispose();
35 | }
36 | GlobalVars.Loggi.Debug("UserListHelper: Successfully retrieved {Count} AD users", ADUsers.Count);
37 | return ADUsers;
38 | }
39 | catch (ActiveDirectoryObjectNotFoundException adEx)
40 | {
41 | GlobalVars.Loggi.Warning(adEx, "UserListHelper: Active Directory not available");
42 | return ADUsers;
43 | }
44 | catch (PrincipalServerDownException psEx)
45 | {
46 | GlobalVars.Loggi.Warning(psEx, "UserListHelper: Domain controller is not available");
47 | return ADUsers;
48 | }
49 | catch (Exception ex)
50 | {
51 | GlobalVars.Loggi.Error(ex, "UserListHelper: Error retrieving AD users");
52 | return ADUsers;
53 | }
54 | }
55 |
56 | private const int UF_ACCOUNTDISABLE = 0x0002;
57 | public static List GetLocalUsers()
58 | {
59 | var users = new List();
60 | try
61 | {
62 | var path = string.Format("WinNT://{0},computer", Environment.MachineName);
63 | using var computerEntry = new DirectoryEntry(path);
64 | foreach (DirectoryEntry childEntry in computerEntry.Children)
65 | {
66 | if (childEntry.SchemaClassName == "User")// filter all users
67 | {
68 | if (((int)childEntry.Properties["UserFlags"].Value & UF_ACCOUNTDISABLE) != UF_ACCOUNTDISABLE)// only if accounts are enabled
69 | {
70 | users.Add(childEntry.Name); // add active user to list
71 | }
72 | }
73 | }
74 | return users;
75 | }
76 | catch (Exception)
77 | {
78 | return users;
79 | }
80 | }
81 |
82 | public static List GetAllUsers()
83 | {
84 | var allUsers = new List();
85 | try
86 | {
87 | var localUsers = GetLocalUsers();
88 | foreach (var user in localUsers)
89 | {
90 | allUsers.Add(user);
91 | }
92 |
93 | var adUsers = GetADUsers();
94 | foreach (var user in adUsers)
95 | {
96 | // Avoid duplicates
97 | if (!allUsers.Contains(user))
98 | {
99 | allUsers.Add(user);
100 | }
101 | }
102 |
103 | GlobalVars.Loggi.Debug("UserListHelper: Successfully retrieved {Count} total users ({LocalCount} local, {ADCount} AD)",
104 | allUsers.Count, localUsers.Count, adUsers.Count);
105 | return allUsers;
106 | }
107 | catch (Exception ex)
108 | {
109 | GlobalVars.Loggi.Error(ex, "UserListHelper: Error retrieving all users");
110 | return allUsers;
111 | }
112 | }
113 |
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/RunAsAdmin/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // Dieser Code wurde von einem Tool generiert.
4 | // Laufzeitversion:4.0.30319.42000
5 | //
6 | // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
7 | // der Code erneut generiert wird.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace RunAsAdmin.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
17 | ///
18 | // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
19 | // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
20 | // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
21 | // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RunAsAdmin.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
51 | /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
65 | ///
66 | internal static System.Drawing.Icon imageres_105 {
67 | get {
68 | object obj = ResourceManager.GetObject("imageres_105", resourceCulture);
69 | return ((System.Drawing.Icon)(obj));
70 | }
71 | }
72 |
73 | ///
74 | /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
75 | ///
76 | internal static System.Drawing.Icon imageres_106 {
77 | get {
78 | object obj = ResourceManager.GetObject("imageres_106", resourceCulture);
79 | return ((System.Drawing.Icon)(obj));
80 | }
81 | }
82 |
83 | ///
84 | /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
85 | ///
86 | internal static System.Drawing.Icon imageres_107 {
87 | get {
88 | object obj = ResourceManager.GetObject("imageres_107", resourceCulture);
89 | return ((System.Drawing.Icon)(obj));
90 | }
91 | }
92 |
93 | ///
94 | /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Icon ähnlich wie (Symbol).
95 | ///
96 | internal static System.Drawing.Icon imageres_78 {
97 | get {
98 | object obj = ResourceManager.GetObject("imageres_78", resourceCulture);
99 | return ((System.Drawing.Icon)(obj));
100 | }
101 | }
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | 
3 | 
4 | 
5 |
6 | # RunAsAdmin
7 |
8 | A powerful Windows utility that enables administrators to start applications with elevated privileges while logged in as a standard user. Perfect for IT professionals managing workstations in enterprise environments.
9 |
10 | ## Features
11 |
12 | - **🔐 Secure Credential Storage**: Passwords are encrypted using Windows DPAPI (Data Protection API)
13 | - **👥 User Management**:
14 | - Supports both local and Active Directory users
15 | - Automatic discovery of cached AD users from local profiles
16 | - Works seamlessly in non-AD environments
17 | - **🌐 Multi-Domain Support**: Automatically detects and lists available domains
18 | - **🚀 UAC Integration**: Leverages Windows UAC for secure privilege elevation
19 | - **📝 Comprehensive Logging**: Detailed logging with Serilog and LiteDB for troubleshooting
20 | - **🎨 Modern UI**: Built with MahApps.Metro for a sleek, modern interface
21 | - **🔄 Auto-Update**: Automatic update checks via GitHub releases
22 | - **🖥️ Single-File Deployment**: Optimized for single-file publishing
23 |
24 | ## Getting Started
25 | You can easily download and run the program [here](https://github.com/HendrikKoelbel/RunAsAdmin/releases/latest)
26 |
27 | ### Prerequisites
28 |
29 | **Required:**
30 | - .NET 8.0 Desktop Runtime (LTS)
31 | - Windows Operating System
32 |
33 | **Download .NET 8.0 Runtime:**
34 |
35 | | Architecture | Download Link |
36 | |--------------|---------------|
37 | | **x64** (most common) | [Download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-desktop-8.0.22-windows-x64-installer) |
38 | | **x86** (32-bit) | [Download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-desktop-8.0.22-windows-x86-installer) |
39 | | **ARM64** | [Download](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-desktop-8.0.22-windows-arm64-installer) |
40 |
41 | ### Installation
42 |
43 | 1. Download the latest release from [Releases](https://github.com/HendrikKoelbel/RunAsAdmin/releases/latest)
44 | 2. Extract the ZIP file to your desired location
45 | 3. Run `RunAsAdmin.exe`
46 |
47 | **Note:** The application must be run from a local drive (not from a network share).
48 |
49 | ## How It Works
50 |
51 | 1. **Launch the Application**: Start RunAsAdmin.exe with administrator privileges
52 | 2. **Select Credentials**: Choose or enter domain/username and password
53 | 3. **Select Program**: Click "Start Program with Admin Rights" and select the executable
54 | 4. **Automatic Elevation**: The selected program runs with elevated privileges using the specified credentials
55 |
56 | ## Built With
57 |
58 | ### Core Dependencies
59 |
60 | * **[UACHelper](https://github.com/falahati/UACHelper)** - UAC (User Account Control) management and detection
61 | * **[SimpleImpersonation](https://github.com/mj1856/SimpleImpersonation)** - User impersonation for .NET applications
62 | * **[Onova](https://github.com/Tyrrrz/Onova)** - Auto-update framework with GitHub integration
63 | * **[Config.Net.Json](https://github.com/aloneguid/config)** - Configuration management library
64 | * **[LiteDB](https://github.com/mbdavid/litedb)** - NoSQL document database for logging storage
65 | * **[Serilog.Sinks.LiteDB](https://github.com/serilog/serilog)** - Structured logging with LiteDB sink
66 |
67 | ### UI & Presentation
68 |
69 | * **[MahApps.Metro](https://github.com/MahApps/MahApps.Metro)** - Modern WPF UI framework
70 | * **[MahApps.Metro.IconPacks](https://github.com/MahApps/MahApps.Metro.IconPacks)** - Icon library for Metro-styled applications
71 | * **[ControlzEx](https://github.com/ControlzEx/ControlzEx)** - Shared controls for MahApps.Metro
72 |
73 | ### Utilities
74 |
75 | * **[Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json)** - High-performance JSON framework
76 | * **[TaskScheduler](https://github.com/dahall/TaskScheduler)** - Windows Task Scheduler wrapper
77 | * **[Trinet.Core.IO.Ntfs](https://github.com/RichardD2/NTFS-Streams)** - NTFS Alternate Data Streams support
78 | * **[Castle.Core](https://github.com/castleproject/Core)** - Core library for dynamic proxy generation
79 |
80 | ### Windows Integration
81 |
82 | * **System.DirectoryServices** - Active Directory integration
83 | * **System.DirectoryServices.AccountManagement** - User and group management
84 | * **System.Configuration.ConfigurationManager** - Configuration file management
85 | * **System.IO.FileSystem.AccessControl** - File system security management
86 |
87 | ## Versioning
88 |
89 | For the versions available, see the [tags on this repository](https://github.com/HendrikKoelbel/RunAsAdmin/tags).
90 |
91 | ## Authors
92 |
93 | * **Hendrik Koelbel** - *Initial work* - [HendrikKoelbel](https://github.com/HendrikKoelbel)
94 |
95 | See also the list of [contributors](https://github.com/HendrikKoelbel/RunAsAdmin/contributors) who participated in this project.
96 |
97 | ## License
98 |
99 | This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details
100 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/SettingsWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Shapes;
14 | using ControlzEx.Theming;
15 | using MahApps.Metro.Controls;
16 |
17 | namespace RunAsAdmin.Views
18 | {
19 | ///
20 | /// Interaktionslogik für SettingsWindow.xaml
21 | ///
22 | public partial class SettingsWindow : MetroWindow
23 | {
24 | public SettingsWindow()
25 | {
26 | InitializeComponent();
27 | InitializeSettings();
28 | }
29 |
30 | private void InitializeSettings()
31 | {
32 | SwitchThemeToggle.Toggled -= SwitchThemeToggle_Toggled;
33 | SwitchThemeToggle.IsOn = true ? GlobalVars.SettingsHelper.Theme == ThemeManager.BaseColorDark : false;
34 | SwitchThemeToggle.Toggled += SwitchThemeToggle_Toggled;
35 | SwitchAccentComboBox.SelectionChanged -= SwitchAccentComboBox_SelectionChanged;
36 | SwitchAccentComboBox.ItemsSource = Enum.GetValues(typeof(GlobalVars.Accents));
37 | SwitchAccentComboBox.SelectedIndex = SwitchAccentComboBox.Items.IndexOf((GlobalVars.Accents)Enum.Parse(typeof(GlobalVars.Accents), GlobalVars.SettingsHelper.Accent));
38 | SwitchAccentComboBox.SelectionChanged += SwitchAccentComboBox_SelectionChanged;
39 | }
40 |
41 | private void SwitchThemeToggle_Toggled(object sender, RoutedEventArgs e)
42 | {
43 | try
44 | {
45 | if (SwitchThemeToggle.IsOn == true)
46 | {
47 | // Switch Theme
48 | ThemeManager.Current.ChangeTheme(Application.Current, ThemeManager.Current.GetInverseTheme(ThemeManager.Current.DetectTheme(Application.Current)));
49 | // Display current theme on the SwitchLabel
50 | SwitchThemeToggle.OnContent = ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme;
51 | // Save current theme in the settings
52 | GlobalVars.SettingsHelper.Theme = ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme;
53 | // Log this event
54 | GlobalVars.Loggi.Information($"Theme was changed from {ThemeManager.Current.GetInverseTheme(ThemeManager.Current.DetectTheme(Application.Current)).BaseColorScheme} to {ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme}");
55 | }
56 | else
57 | {
58 | // Switch Theme
59 | ThemeManager.Current.ChangeTheme(Application.Current, ThemeManager.Current.GetInverseTheme(ThemeManager.Current.DetectTheme(Application.Current)));
60 | // Display current theme on the SwitchLabel
61 | SwitchThemeToggle.OffContent = ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme;
62 | // Save current theme in the settings
63 | GlobalVars.SettingsHelper.Theme = ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme;
64 | // Log this event
65 | GlobalVars.Loggi.Information($"Theme was changed from {ThemeManager.Current.GetInverseTheme(ThemeManager.Current.DetectTheme(Application.Current)).BaseColorScheme} to {ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme}");
66 | }
67 | }
68 | catch (Exception ex)
69 | {
70 | GlobalVars.Loggi.Error(ex, ex.Message);
71 | }
72 | }
73 | private void SwitchThemeButton_Click(object sender, RoutedEventArgs e)
74 | {
75 | try
76 | {
77 | ThemeManager.Current.ChangeTheme(Application.Current, ThemeManager.Current.GetInverseTheme(ThemeManager.Current.DetectTheme(Application.Current)));
78 | GlobalVars.SettingsHelper.Theme = ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme;
79 | GlobalVars.Loggi.Information($"Theme was changed from {ThemeManager.Current.GetInverseTheme(ThemeManager.Current.DetectTheme(Application.Current)).BaseColorScheme} to {ThemeManager.Current.DetectTheme(Application.Current).BaseColorScheme}");
80 | }
81 | catch (Exception ex)
82 | {
83 | GlobalVars.Loggi.Error(ex, ex.Message);
84 | }
85 | }
86 |
87 | private void SwitchAccentComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
88 | {
89 | try
90 | {
91 | ThemeManager.Current.ChangeThemeColorScheme(Application.Current, SwitchAccentComboBox.SelectedItem.ToString());
92 | GlobalVars.SettingsHelper.Accent = SwitchAccentComboBox.SelectedItem.ToString();
93 | GlobalVars.Loggi.Information($"Accent was changed to {SwitchAccentComboBox.SelectedItem.ToString()}");
94 | }
95 | catch (Exception ex)
96 | {
97 | GlobalVars.Loggi.Error(ex, ex.Message);
98 | }
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/RunAsAdmin/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 |
122 | ..\Resources\imageres_105.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
123 |
124 |
125 | ..\Resources\imageres_106.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
126 |
127 |
128 | ..\Resources\imageres_107.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
129 |
130 |
131 | ..\Resources\imageres_78.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
132 |
133 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
341 | RunAsAdmin_Debug.zip
342 | RunAsAdmin.zip
343 |
--------------------------------------------------------------------------------
/RunAsAdmin/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using ControlzEx.Theming;
2 | using RunAsAdmin.Views;
3 | using System;
4 | using System.IO;
5 | using System.Threading;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 |
9 | namespace RunAsAdmin
10 | {
11 | ///
12 | /// Interaction logic for App.xaml
13 | ///
14 | public partial class App : Application
15 | {
16 | public App()
17 | {
18 | Startup += new StartupEventHandler(App_Startup); // Can be called from XAML
19 |
20 | DispatcherUnhandledException += App_DispatcherUnhandledException; //Example 2
21 |
22 | TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; //Example 4
23 |
24 | System.Windows.Forms.Application.ThreadException += WinFormApplication_ThreadException; //Example 5
25 | }
26 |
27 | private void App_Startup(object sender, StartupEventArgs e)
28 | {
29 | //Here if called from XAML, otherwise, this code can be in App()
30 | AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Example 3
31 | }
32 | #region Catch UnhandledExceptions
33 |
34 | // Example 2
35 | private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
36 | {
37 | GlobalVars.Loggi.Error(e.Exception, e.Exception.Message);
38 | MessageBox.Show(e.Exception.Message);
39 | e.Handled = true;
40 | }
41 |
42 | // Example 3
43 | private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
44 | {
45 | var exception = e.ExceptionObject as Exception;
46 | GlobalVars.Loggi.Error(exception, exception.Message);
47 | MessageBox.Show(exception.Message);
48 | if (e.IsTerminating)
49 | {
50 | GlobalVars.Loggi.Fatal(exception, exception.Message);
51 | MessageBox.Show(exception.Message);
52 | //Now is a good time to write that critical error file!
53 | }
54 | }
55 |
56 | // Example 4
57 | private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
58 | {
59 | GlobalVars.Loggi.Error(e.Exception, e.Exception.Message);
60 | MessageBox.Show(e.Exception.Message);
61 | e.SetObserved();
62 | }
63 |
64 | // Example 5
65 | private void WinFormApplication_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
66 | {
67 | GlobalVars.Loggi.Error(e.Exception, e.Exception.Message);
68 | MessageBox.Show(e.Exception.Message);
69 | }
70 | #endregion
71 |
72 | protected override async void OnStartup(StartupEventArgs e)
73 | {
74 | base.OnStartup(e);
75 |
76 | //Initialize the splash screen and set it as the application main window
77 | var splashScreen = new SplashScreenWindow();
78 | this.MainWindow = splashScreen;
79 | splashScreen.Show();
80 | splashScreen.SplashScreenInfoLabel.Content = "Loading Application...";
81 | await InitializeIOFolders();
82 | InitializeStyleAsync();
83 |
84 | //In order to ensure the UI stays responsive, we need to
85 | //Do the work on a different thread
86 | await Task.Factory.StartNew(() =>
87 | {
88 | try
89 | {
90 | //we need to do the work in batches so that we can report progress
91 | for (int i = 1; i <= 100; i++)
92 | {
93 |
94 | //Simulate a part of work being done
95 | Thread.Sleep(10);
96 |
97 | //Because we're not on the UI thread, we need to use the Dispatcher
98 | //Associated with the splash screen to update the progress bar
99 | splashScreen.SplashScreenProgressBar.Dispatcher.Invoke(() => splashScreen.SplashScreenProgressBar.IsIndeterminate = true);
100 |
101 | }
102 |
103 | //Once we're done we need to use the Dispatcher
104 | //to create and show the MainWindow
105 | this.Dispatcher.Invoke(() =>
106 | {
107 | //Initialize the main window, set it as the application main window
108 | //and close the splash screen
109 | var mainWindow = new MainWindow();
110 | this.MainWindow = mainWindow;
111 | mainWindow.Show();
112 | mainWindow.Activate();
113 | splashScreen.Close();
114 | });
115 | }
116 | catch (Exception ex)
117 | {
118 | GlobalVars.Loggi.Error(ex, ex.Message);
119 | }
120 | });
121 | }
122 |
123 | public static void InitializeStyleAsync()
124 | {
125 | try
126 | {
127 | if (File.Exists(GlobalVars.SettingsPath))
128 | {
129 | if (!string.IsNullOrEmpty(GlobalVars.SettingsHelper.Theme))
130 | {
131 | if (Enum.TryParse(GlobalVars.SettingsHelper.Theme, out GlobalVars.Themes ThemesResult))
132 | switch (ThemesResult)
133 | {
134 | case GlobalVars.Themes.Dark:
135 | ThemeManager.Current.ChangeThemeBaseColor(Application.Current,
136 | ThemeManager.BaseColorDark);
137 | break;
138 | case GlobalVars.Themes.Light:
139 | ThemeManager.Current.ChangeThemeBaseColor(Application.Current,
140 | ThemeManager.BaseColorLight);
141 | break;
142 | default:
143 | break;
144 | }
145 | }
146 |
147 | if (!string.IsNullOrEmpty(GlobalVars.SettingsHelper.Accent))
148 | {
149 | if (Enum.TryParse(GlobalVars.SettingsHelper.Accent, out GlobalVars.Accents AccentResult))
150 | ThemeManager.Current.ChangeThemeColorScheme(Application.Current,
151 | AccentResult.ToString());
152 | }
153 | }
154 | }
155 | catch (Exception ex)
156 | {
157 | GlobalVars.Loggi.Error(ex, ex.Message);
158 | }
159 | }
160 | public async Task InitializeIOFolders()
161 | {
162 | try
163 | {
164 | await Task.Run(() =>
165 | {
166 | foreach (var Path in GlobalVars.ListOfPaths)
167 | {
168 | if (!Directory.Exists(Path))
169 | {
170 | Directory.CreateDirectory(Path);
171 | if (Directory.Exists(GlobalVars.PublicDocumentsWithAssemblyName))
172 | GlobalVars.Loggi.Debug("Folder was not found and created:\n{0}", Path);
173 | }
174 | }
175 | });
176 | }
177 | catch (Exception ex)
178 | {
179 | GlobalVars.Loggi.Error(ex, ex.Message);
180 | }
181 | }
182 | }
183 | }
--------------------------------------------------------------------------------
/RunAsAdmin/Core/DirectoryHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Security.AccessControl;
6 | using System.Security.Principal;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 |
10 | namespace RunAsAdmin.Core
11 | {
12 | public static class DirectoryHelper
13 | {
14 | public static bool HasDirectoryRights(string directoryPath, FileSystemRights rights, string winUserString = null, WindowsIdentity winUser = null)
15 | {
16 | try
17 | {
18 | if (string.IsNullOrWhiteSpace(directoryPath))
19 | {
20 | GlobalVars.Loggi.Warning("HasDirectoryRights called with null or empty directoryPath");
21 | return false;
22 | }
23 |
24 | if (!Directory.Exists(directoryPath))
25 | {
26 | GlobalVars.Loggi.Warning("Directory does not exist: {DirectoryPath}", directoryPath);
27 | return false;
28 | }
29 |
30 | var ds = new DirectorySecurity();
31 | DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
32 | ds = FileSystemAclExtensions.GetAccessControl(dirInfo);
33 | var rules = ds.GetAccessRules(true, true, typeof(SecurityIdentifier));
34 |
35 | if (winUserString != null)
36 | {
37 | return rules.OfType().Any(r =>
38 | ((int)r.FileSystemRights & (int)rights) != 0 && r.IdentityReference.Value == winUserString);
39 | }
40 | else if (winUser != null)
41 | {
42 | return rules.OfType().Any(r =>
43 | ((int)r.FileSystemRights & (int)rights) != 0 && r.IdentityReference.Value == winUser.User.Value);
44 | }
45 |
46 | GlobalVars.Loggi.Warning("HasDirectoryRights called without valid user identifier");
47 | return false;
48 | }
49 | catch (UnauthorizedAccessException uaEx)
50 | {
51 | GlobalVars.Loggi.Warning(uaEx, "Access denied when checking directory rights for: {DirectoryPath}", directoryPath);
52 | return false;
53 | }
54 | catch (Exception ex)
55 | {
56 | GlobalVars.Loggi.Error(ex, "Error checking directory rights for: {DirectoryPath}", directoryPath);
57 | return false;
58 | }
59 | }
60 |
61 | public static void AddDirectorySecurity(string directoryPath, string winUserString = null, WindowsIdentity winUser = null,
62 | FileSystemRights rights = FileSystemRights.FullControl, InheritanceFlags inheritanceFlags = InheritanceFlags.ObjectInherit, PropagationFlags propagationFlags = PropagationFlags.None, AccessControlType controlType = AccessControlType.Allow)
63 | {
64 | try
65 | {
66 | if (string.IsNullOrWhiteSpace(directoryPath))
67 | {
68 | GlobalVars.Loggi.Error("AddDirectorySecurity called with null or empty directoryPath");
69 | throw new ArgumentNullException(nameof(directoryPath));
70 | }
71 |
72 | if (!Directory.Exists(directoryPath))
73 | {
74 | GlobalVars.Loggi.Error("Cannot add security to non-existent directory: {DirectoryPath}", directoryPath);
75 | throw new DirectoryNotFoundException($"Directory not found: {directoryPath}");
76 | }
77 |
78 | // Create a new DirectoryInfo object.
79 | DirectoryInfo dInfo = new DirectoryInfo(directoryPath);
80 | // Get a DirectorySecurity object that represents the
81 | // current security settings.
82 | DirectorySecurity dSecurity = dInfo.GetAccessControl();
83 | if (winUserString != null)
84 | {
85 | // Add the FileSystemAccessRule to the security settings.
86 | dSecurity.AddAccessRule(new FileSystemAccessRule(winUserString, rights, inheritanceFlags, propagationFlags, controlType));
87 | GlobalVars.Loggi.Information("Added directory security for user: {User} on {Path}", winUserString, directoryPath);
88 | }
89 | else if (winUser != null)
90 | {
91 | // Add the FileSystemAccessRule to the security settings.
92 | dSecurity.AddAccessRule(new FileSystemAccessRule(winUser.User.Value, rights, inheritanceFlags, propagationFlags, controlType));
93 | GlobalVars.Loggi.Information("Added directory security for user: {User} on {Path}", winUser.Name, directoryPath);
94 | }
95 | else
96 | {
97 | GlobalVars.Loggi.Error("AddDirectorySecurity called without valid user identifier");
98 | throw new ArgumentException("Either winUserString or winUser must be provided");
99 | }
100 | // Set the new access settings.
101 | dInfo.SetAccessControl(dSecurity);
102 | }
103 | catch (UnauthorizedAccessException uaEx)
104 | {
105 | GlobalVars.Loggi.Error(uaEx, "Access denied when adding directory security for: {DirectoryPath}", directoryPath);
106 | throw;
107 | }
108 | catch (Exception ex)
109 | {
110 | GlobalVars.Loggi.Error(ex, "Error adding directory security for: {DirectoryPath}", directoryPath);
111 | throw;
112 | }
113 | }
114 |
115 | public static void RemoveDirectorySecurity(string directoryPath, string winUserString = null, WindowsIdentity winUser = null,
116 | FileSystemRights rights = FileSystemRights.FullControl, InheritanceFlags inheritanceFlags = InheritanceFlags.ContainerInherit, PropagationFlags propagationFlags = PropagationFlags.None, AccessControlType controlType = AccessControlType.Allow)
117 | {
118 | try
119 | {
120 | if (string.IsNullOrWhiteSpace(directoryPath))
121 | {
122 | GlobalVars.Loggi.Error("RemoveDirectorySecurity called with null or empty directoryPath");
123 | throw new ArgumentNullException(nameof(directoryPath));
124 | }
125 |
126 | if (!Directory.Exists(directoryPath))
127 | {
128 | GlobalVars.Loggi.Error("Cannot remove security from non-existent directory: {DirectoryPath}", directoryPath);
129 | throw new DirectoryNotFoundException($"Directory not found: {directoryPath}");
130 | }
131 |
132 | // Create a new DirectoryInfo object.
133 | DirectoryInfo dInfo = new DirectoryInfo(directoryPath);
134 | // Get a DirectorySecurity object that represents the
135 | // current security settings.
136 | DirectorySecurity dSecurity = dInfo.GetAccessControl();
137 | if (winUserString != null)
138 | {
139 | // Removes the FileSystemAccessRule to the security settings.
140 | dSecurity.RemoveAccessRule(new FileSystemAccessRule(winUserString, rights, inheritanceFlags, propagationFlags, controlType));
141 | GlobalVars.Loggi.Information("Removed directory security for user: {User} on {Path}", winUserString, directoryPath);
142 | }
143 | else if (winUser != null)
144 | {
145 | // Removes the FileSystemAccessRule to the security settings.
146 | dSecurity.RemoveAccessRule(new FileSystemAccessRule(winUser.User.Value, rights, inheritanceFlags, propagationFlags, controlType));
147 | GlobalVars.Loggi.Information("Removed directory security for user: {User} on {Path}", winUser.Name, directoryPath);
148 | }
149 | else
150 | {
151 | GlobalVars.Loggi.Error("RemoveDirectorySecurity called without valid user identifier");
152 | throw new ArgumentException("Either winUserString or winUser must be provided");
153 | }
154 | // Set the new access settings.
155 | dInfo.SetAccessControl(dSecurity);
156 | }
157 | catch (UnauthorizedAccessException uaEx)
158 | {
159 | GlobalVars.Loggi.Error(uaEx, "Access denied when removing directory security for: {DirectoryPath}", directoryPath);
160 | throw;
161 | }
162 | catch (Exception ex)
163 | {
164 | GlobalVars.Loggi.Error(ex, "Error removing directory security for: {DirectoryPath}", directoryPath);
165 | throw;
166 | }
167 | }
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/RunAsAdmin/Core/SecurityHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Security.Cryptography;
4 | using System.Text;
5 |
6 | namespace RunAsAdmin.Core
7 | {
8 | ///
9 | /// Provides secure encryption/decryption using AES-256 with PBKDF2 key derivation
10 | /// and Windows DPAPI for additional security layer
11 | ///
12 | public static class SecurityHelper
13 | {
14 | // Using DPAPI for Windows-specific secure encryption
15 | // This eliminates the need for hardcoded keys and provides per-user encryption
16 | private static readonly DataProtectionScope ProtectionScope = DataProtectionScope.CurrentUser;
17 |
18 | // Additional entropy for DPAPI (acts as a secondary password)
19 | private static readonly byte[] AdditionalEntropy = Encoding.UTF8.GetBytes("RunAsAdmin_Security_v2.0");
20 |
21 | ///
22 | /// Encrypts a string using Windows DPAPI with AES-256 encryption
23 | ///
24 | /// The plaintext string to encrypt
25 | /// Base64-encoded encrypted string, or null if input is null/empty
26 | public static string Encrypt(string textToEncrypt)
27 | {
28 | try
29 | {
30 | if (string.IsNullOrEmpty(textToEncrypt))
31 | {
32 | GlobalVars.Loggi.Warning("Encrypt called with null or empty string");
33 | return null;
34 | }
35 |
36 | // Convert string to byte array
37 | byte[] plaintextBytes = Encoding.UTF8.GetBytes(textToEncrypt);
38 |
39 | // Use Windows DPAPI for encryption
40 | byte[] encryptedBytes = ProtectedData.Protect(
41 | plaintextBytes,
42 | AdditionalEntropy,
43 | ProtectionScope);
44 |
45 | // Convert to Base64 for storage
46 | string encryptedText = Convert.ToBase64String(encryptedBytes);
47 |
48 | GlobalVars.Loggi.Debug("Successfully encrypted data");
49 | return encryptedText;
50 | }
51 | catch (CryptographicException cryptoEx)
52 | {
53 | GlobalVars.Loggi.Error(cryptoEx, "Cryptographic error during encryption: {Message}", cryptoEx.Message);
54 | throw new InvalidOperationException("Failed to encrypt data. Ensure you have proper permissions.", cryptoEx);
55 | }
56 | catch (Exception ex)
57 | {
58 | GlobalVars.Loggi.Error(ex, "Unexpected error during encryption: {Message}", ex.Message);
59 | throw new InvalidOperationException("Encryption failed", ex);
60 | }
61 | }
62 |
63 | ///
64 | /// Decrypts a string that was encrypted using the Encrypt method
65 | ///
66 | /// Base64-encoded encrypted string
67 | /// Decrypted plaintext string, or null if input is null/empty
68 | public static string Decrypt(string textToDecrypt)
69 | {
70 | try
71 | {
72 | if (string.IsNullOrEmpty(textToDecrypt))
73 | {
74 | GlobalVars.Loggi.Warning("Decrypt called with null or empty string");
75 | return string.Empty;
76 | }
77 |
78 | // Convert from Base64
79 | byte[] encryptedBytes = Convert.FromBase64String(textToDecrypt.Replace(" ", "+"));
80 |
81 | // Use Windows DPAPI for decryption
82 | byte[] decryptedBytes = ProtectedData.Unprotect(
83 | encryptedBytes,
84 | AdditionalEntropy,
85 | ProtectionScope);
86 |
87 | // Convert back to string
88 | string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
89 |
90 | GlobalVars.Loggi.Debug("Successfully decrypted data");
91 | return decryptedText;
92 | }
93 | catch (FormatException formatEx)
94 | {
95 | GlobalVars.Loggi.Warning(formatEx, "Invalid Base64 format during decryption, returning empty string");
96 | return string.Empty;
97 | }
98 | catch (CryptographicException cryptoEx)
99 | {
100 | GlobalVars.Loggi.Warning(cryptoEx, "Cryptographic error during decryption (data may be encrypted by different user/machine), returning empty string");
101 | return string.Empty;
102 | }
103 | catch (Exception ex)
104 | {
105 | GlobalVars.Loggi.Warning(ex, "Unexpected error during decryption, returning empty string");
106 | return string.Empty;
107 | }
108 | }
109 |
110 | ///
111 | /// Legacy method for migrating old DES-encrypted data to new DPAPI encryption
112 | /// This should only be used during migration and then removed
113 | ///
114 | [Obsolete("This method is only for migrating legacy DES/AES encrypted data. Use Encrypt/Decrypt instead.")]
115 | public static string MigrateLegacyEncryption(string legacyEncrypted, bool useDES)
116 | {
117 | try
118 | {
119 | if (string.IsNullOrEmpty(legacyEncrypted))
120 | return null;
121 |
122 | string decrypted = DecryptLegacy(legacyEncrypted, useDES);
123 | string newEncrypted = Encrypt(decrypted);
124 |
125 | GlobalVars.Loggi.Information("Successfully migrated legacy encrypted data");
126 | return newEncrypted;
127 | }
128 | catch (Exception ex)
129 | {
130 | GlobalVars.Loggi.Error(ex, "Failed to migrate legacy encryption: {Message}", ex.Message);
131 | throw;
132 | }
133 | }
134 |
135 | ///
136 | /// Decrypts legacy DES or AES encrypted data
137 | ///
138 | private static string DecryptLegacy(string textToDecrypt, bool useDES)
139 | {
140 | string _key = "Lf7Xw5g8GFczu$^&6bJfhfjXa6";
141 | string _iv = "T4-+6t*C=-c7uP$2h?S^&PG";
142 |
143 | byte[] inputbyteArray = Convert.FromBase64String(textToDecrypt.Replace(" ", "+"));
144 |
145 | if (useDES)
146 | {
147 | // Legacy DES decryption
148 | byte[] _ivByte = Encoding.UTF8.GetBytes(_iv.Substring(0, 8));
149 | byte[] _keybyte = Encoding.UTF8.GetBytes(_key.Substring(0, 8));
150 |
151 | using (var des = new DESCryptoServiceProvider())
152 | using (var ms = new MemoryStream())
153 | using (var cs = new CryptoStream(ms, des.CreateDecryptor(_keybyte, _ivByte), CryptoStreamMode.Write))
154 | {
155 | cs.Write(inputbyteArray, 0, inputbyteArray.Length);
156 | cs.FlushFinalBlock();
157 | return Encoding.UTF8.GetString(ms.ToArray());
158 | }
159 | }
160 | else
161 | {
162 | // Legacy AES decryption
163 | byte[] _ivByte = Encoding.UTF8.GetBytes(_iv.Substring(0, 16));
164 | byte[] _keybyte = Encoding.UTF8.GetBytes(_key.Substring(0, 16));
165 |
166 | using (var aes = Aes.Create())
167 | using (var ms = new MemoryStream())
168 | using (var cs = new CryptoStream(ms, aes.CreateDecryptor(_keybyte, _ivByte), CryptoStreamMode.Write))
169 | {
170 | aes.Key = _keybyte;
171 | aes.IV = _ivByte;
172 | cs.Write(inputbyteArray, 0, inputbyteArray.Length);
173 | cs.FlushFinalBlock();
174 | return Encoding.UTF8.GetString(ms.ToArray());
175 | }
176 | }
177 | }
178 | }
179 | }
180 |
--------------------------------------------------------------------------------
/.github/scripts/check-version.ps1:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env pwsh
2 | <#
3 | .SYNOPSIS
4 | Checks if the project version has changed compared to the latest GitHub release.
5 |
6 | .DESCRIPTION
7 | This script extracts the version from AssemblyInfo.cs, compares it with the
8 | latest GitHub release version, and determines if a new release should be created.
9 |
10 | .PARAMETER AssemblyInfoPath
11 | Path to the AssemblyInfo.cs file
12 |
13 | .PARAMETER GitHubRepo
14 | GitHub repository in format "owner/repo"
15 |
16 | .PARAMETER GitHubToken
17 | GitHub token for API authentication
18 | #>
19 |
20 | param(
21 | [Parameter(Mandatory=$true)]
22 | [string]$AssemblyInfoPath,
23 |
24 | [Parameter(Mandatory=$true)]
25 | [string]$GitHubRepo,
26 |
27 | [Parameter(Mandatory=$false)]
28 | [string]$GitHubToken = $env:GITHUB_TOKEN
29 | )
30 |
31 | # Function to extract version from AssemblyInfo.cs
32 | function Get-AssemblyVersion {
33 | param([string]$FilePath)
34 |
35 | if (-not (Test-Path $FilePath)) {
36 | Write-Error "AssemblyInfo.cs not found at: $FilePath"
37 | exit 1
38 | }
39 |
40 | # Read file line by line to avoid matching commented-out versions
41 | $lines = Get-Content $FilePath
42 |
43 | foreach ($line in $lines) {
44 | # Skip empty lines and comments
45 | if ([string]::IsNullOrWhiteSpace($line) -or $line.TrimStart() -match '^//') {
46 | continue
47 | }
48 |
49 | # Match [assembly: AssemblyVersion("x.x.x")]
50 | if ($line -match '\[assembly:\s*AssemblyVersion\s*\(\s*"([^"]+)"\s*\)\]') {
51 | $version = $matches[1]
52 |
53 | # Check for wildcard version (e.g., "1.0.*")
54 | if ($version -match '\*') {
55 | Write-Host ""
56 | Write-Host "========================================" -ForegroundColor Red
57 | Write-Host "ERROR: Wildcard Version Detected" -ForegroundColor Red
58 | Write-Host "========================================" -ForegroundColor Red
59 | Write-Host ""
60 | Write-Host "AssemblyVersion contains wildcard: $version" -ForegroundColor Yellow
61 | Write-Host ""
62 | Write-Host "The automated release workflow requires a fixed version number." -ForegroundColor Yellow
63 | Write-Host "Wildcard versions (e.g., '1.0.*') cannot be used for version comparison." -ForegroundColor Yellow
64 | Write-Host ""
65 | Write-Host "Please update the AssemblyInfo.cs file with a fixed version:" -ForegroundColor Cyan
66 | Write-Host " File: $FilePath" -ForegroundColor White
67 | Write-Host " Current: [assembly: AssemblyVersion(`"$version`")]" -ForegroundColor Red
68 | Write-Host " Example: [assembly: AssemblyVersion(`"2.0.3`")]" -ForegroundColor Green
69 | Write-Host ""
70 | Write-Host "Steps to fix:" -ForegroundColor Cyan
71 | Write-Host " 1. Edit $FilePath" -ForegroundColor White
72 | Write-Host " 2. Replace wildcard version with fixed version (e.g., 2.0.3)" -ForegroundColor White
73 | Write-Host " 3. Also update AssemblyFileVersion to match" -ForegroundColor White
74 | Write-Host " 4. Commit and push the changes" -ForegroundColor White
75 | Write-Host ""
76 | Write-Host "========================================" -ForegroundColor Red
77 | Write-Error "Wildcard version detected: $version. Please use a fixed version number."
78 | exit 1
79 | }
80 |
81 | return $version
82 | }
83 | }
84 |
85 | Write-Error "Could not extract version from AssemblyInfo.cs"
86 | exit 1
87 | }
88 |
89 | # Function to get latest GitHub release version
90 | function Get-LatestGitHubRelease {
91 | param(
92 | [string]$Repo,
93 | [string]$Token
94 | )
95 |
96 | $headers = @{
97 | "Accept" = "application/vnd.github.v3+json"
98 | "User-Agent" = "GitHub-Actions"
99 | }
100 |
101 | if ($Token) {
102 | $headers["Authorization"] = "Bearer $Token"
103 | }
104 |
105 | $uri = "https://api.github.com/repos/$Repo/releases/latest"
106 |
107 | try {
108 | $response = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get -ErrorAction Stop
109 |
110 | # Extract version from tag_name (remove 'v' prefix if present)
111 | $tagName = $response.tag_name
112 | if ($tagName -match '^v?(.+)$') {
113 | return $matches[1]
114 | }
115 |
116 | return $tagName
117 | }
118 | catch {
119 | if ($_.Exception.Response.StatusCode -eq 404) {
120 | Write-Warning "No releases found for repository $Repo"
121 | return "0.0.0"
122 | }
123 |
124 | Write-Error "Failed to fetch latest release: $_"
125 | exit 1
126 | }
127 | }
128 |
129 | # Function to compare versions
130 | function Compare-Versions {
131 | param(
132 | [string]$Version1,
133 | [string]$Version2
134 | )
135 |
136 | try {
137 | $v1 = [version]$Version1
138 | $v2 = [version]$Version2
139 |
140 | if ($v1 -gt $v2) {
141 | return 1 # Version1 is newer
142 | }
143 | elseif ($v1 -eq $v2) {
144 | return 0 # Versions are equal
145 | }
146 | else {
147 | return -1 # Version1 is older
148 | }
149 | }
150 | catch {
151 | Write-Error "Failed to compare versions: $_"
152 | exit 1
153 | }
154 | }
155 |
156 | # Main execution
157 | Write-Host "========================================" -ForegroundColor Cyan
158 | Write-Host "Version Check for $GitHubRepo" -ForegroundColor Cyan
159 | Write-Host "========================================" -ForegroundColor Cyan
160 | Write-Host ""
161 |
162 | # Get current version from AssemblyInfo.cs
163 | Write-Host "Reading version from: $AssemblyInfoPath" -ForegroundColor Yellow
164 | $currentVersion = Get-AssemblyVersion -FilePath $AssemblyInfoPath
165 | Write-Host " Current version: $currentVersion" -ForegroundColor Green
166 |
167 | # Get latest release version from GitHub
168 | Write-Host "Fetching latest release from GitHub..." -ForegroundColor Yellow
169 | $latestVersion = Get-LatestGitHubRelease -Repo $GitHubRepo -Token $GitHubToken
170 | Write-Host " Latest release: $latestVersion" -ForegroundColor Green
171 |
172 | # Compare versions
173 | Write-Host ""
174 | Write-Host "Comparing versions..." -ForegroundColor Yellow
175 | $comparison = Compare-Versions -Version1 $currentVersion -Version2 $latestVersion
176 |
177 | $shouldRelease = $false
178 | $releaseVersion = "v$currentVersion"
179 |
180 | switch ($comparison) {
181 | 1 {
182 | Write-Host " ✓ Version has INCREASED: $latestVersion -> $currentVersion" -ForegroundColor Green
183 | Write-Host " ✓ A new release SHOULD be created" -ForegroundColor Green
184 | $shouldRelease = $true
185 | }
186 | 0 {
187 | Write-Host " ⚠ Version is UNCHANGED: $currentVersion" -ForegroundColor Yellow
188 | Write-Host " ⚠ No new release needed" -ForegroundColor Yellow
189 | $shouldRelease = $false
190 | }
191 | -1 {
192 | Write-Host " ✗ Version has DECREASED: $latestVersion -> $currentVersion" -ForegroundColor Red
193 | Write-Host " ✗ This is likely an error!" -ForegroundColor Red
194 | Write-Error "Version downgrade detected! Current version ($currentVersion) is older than latest release ($latestVersion)"
195 | exit 1
196 | }
197 | }
198 |
199 | # Set GitHub Actions outputs
200 | Write-Host ""
201 | Write-Host "Setting GitHub Actions outputs..." -ForegroundColor Yellow
202 |
203 | if ($env:GITHUB_OUTPUT) {
204 | Add-Content -Path $env:GITHUB_OUTPUT -Value "current_version=$currentVersion"
205 | Add-Content -Path $env:GITHUB_OUTPUT -Value "latest_version=$latestVersion"
206 | Add-Content -Path $env:GITHUB_OUTPUT -Value "should_release=$($shouldRelease.ToString().ToLower())"
207 | Add-Content -Path $env:GITHUB_OUTPUT -Value "release_version=$releaseVersion"
208 | Add-Content -Path $env:GITHUB_OUTPUT -Value "version_changed=$($shouldRelease.ToString().ToLower())"
209 |
210 | Write-Host " ✓ Outputs written to GITHUB_OUTPUT" -ForegroundColor Green
211 | }
212 | else {
213 | Write-Host " current_version=$currentVersion"
214 | Write-Host " latest_version=$latestVersion"
215 | Write-Host " should_release=$($shouldRelease.ToString().ToLower())"
216 | Write-Host " release_version=$releaseVersion"
217 | Write-Host " version_changed=$($shouldRelease.ToString().ToLower())"
218 | }
219 |
220 | Write-Host ""
221 | Write-Host "========================================" -ForegroundColor Cyan
222 | Write-Host "Version check completed successfully" -ForegroundColor Cyan
223 | Write-Host "========================================" -ForegroundColor Cyan
224 |
225 | exit 0
226 |
--------------------------------------------------------------------------------
/RunAsAdmin/GlobalVars.cs:
--------------------------------------------------------------------------------
1 | using Config.Net;
2 | using Serilog;
3 | using Serilog.Debugging;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Diagnostics;
7 | using System.IO;
8 | using System.Reflection;
9 |
10 | namespace RunAsAdmin
11 | {
12 | public static class GlobalVars
13 | {
14 |
15 | #region AutoUpdater Informations
16 | ///
17 | /// GitHub Username to the userprofile
18 | ///
19 | public static string GitHubUsername => "HendrikKoelbel";
20 | ///
21 | /// GitHub project name to the repository
22 | ///
23 | public static string GitHubProjectName => "RunAsAdmin";
24 | ///
25 | /// Asset name that will be downloaded from the Updater
26 | ///
27 | public static string GitHubAssetName => "RunAsAdmin.zip";
28 | #endregion
29 |
30 | #region Logger
31 | ///
32 | /// Returns the Users\Public\%AppName%\Logger_Year-Month-Day.db file path
33 | ///
34 | public static string LoggerPath => PublicDocumentsWithAssemblyName + "\\Logger_" + DateTime.Now.ToString("yyyy-MM-dd") + ".db";
35 | public static ILogger Loggi => new LoggerConfiguration()
36 | .WriteTo.LiteDB(LoggerPath)
37 | .CreateLogger();
38 | #endregion
39 |
40 | #region Settings
41 | ///
42 | /// Returns the Users\Public\%AppName%\Settings.json file path
43 | ///
44 | public static string SettingsPath => PublicDocumentsWithAssemblyName + "\\Settings.json";
45 | ///
46 | /// Creates the ConfigurationBuilder with the ISettings Interface to get or set settings
47 | ///
48 | public static ISettings SettingsHelper { get; set; } = new ConfigurationBuilder()
49 | .UseJsonFile(SettingsPath)
50 | .Build();
51 | ///
52 | /// Contains all setting values
53 | ///
54 | public interface ISettings
55 | {
56 | [Option(Alias = "Design.Theme", DefaultValue = "Light")]
57 | string Theme { get; set; }
58 | [Option(Alias = "Design.Accent", DefaultValue = "Blue")]
59 | string Accent { get; set; }
60 | [Option(Alias = "UserData.Username", DefaultValue = null)]
61 | public string Username { get; set; }
62 | [Option(Alias = "UserData.Password", DefaultValue = null)]
63 | public string Password { get; set; }
64 | [Option(Alias = "UserData.Domain", DefaultValue = null)]
65 | public string Domain { get; set; }
66 | }
67 | #endregion
68 |
69 | #region Path and File List<>
70 | public static List ListOfPaths => new List
71 | {
72 | PublicDocumentsWithAssemblyName,
73 | TempPathWithAssemblyName,
74 | };
75 | public static List ListOfFiles => new List
76 | {
77 | LoggerPath,
78 | SettingsPath,
79 | };
80 | #endregion
81 |
82 | #region SpecialFolder Paths
83 | ///
84 | /// Returns the AppData\Roaming Path
85 | ///
86 | public static string AppDataRoaming => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
87 | ///
88 | /// Returns the AppData\Local Path
89 | ///
90 | public static string AppDataLocal => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
91 | ///
92 | /// Returns the ProgramData Path
93 | ///
94 | public static string ProgramData => Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
95 | ///
96 | /// Returns the Users\Public\Documents\%AppName% Path
97 | ///
98 | public static string PublicDocumentsWithAssemblyName => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), Assembly.GetEntryAssembly().GetName().Name);
99 | ///
100 | /// Returns the local Temp path
101 | ///
102 | public static string TempPath => Path.GetTempPath();
103 | ///
104 | /// Returns a temoprary file path thats created with a unique name and 0 bytes
105 | ///
106 | public static string TempFile => Path.GetTempFileName();
107 | ///
108 | /// Returns the AppData\Local\%AppName% Path
109 | ///
110 | public static string AppDataWithAssemblyName => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Assembly.GetEntryAssembly().GetName().Name);
111 | ///
112 | /// Returns the AppData\Local\Temp\%AppName% Path
113 | ///
114 | public static string TempPathWithAssemblyName => Path.Combine(Path.GetTempPath(), Assembly.GetEntryAssembly().GetName().Name);
115 |
116 | ///
117 | /// Method to get special folders
118 | ///
119 | /// Selection of the special folder
120 | /// Returns the folder path of the selected special folder
121 | public static string GetPath(Environment.SpecialFolder specialFolder)
122 | {
123 | return Environment.GetFolderPath(specialFolder);
124 | }
125 | ///
126 | /// Returns only the path of the application
127 | /// Handles single-file publish scenarios where Assembly.Location is empty
128 | ///
129 | public static string BasePath
130 | {
131 | get
132 | {
133 | // Try Assembly.Location first
134 | string location = Assembly.GetExecutingAssembly().Location;
135 |
136 | // Fallback 1: Environment.ProcessPath (available in .NET 6+)
137 | if (string.IsNullOrEmpty(location))
138 | {
139 | location = Environment.ProcessPath;
140 | }
141 |
142 | // Fallback 2: Process.MainModule.FileName
143 | if (string.IsNullOrEmpty(location))
144 | {
145 | try
146 | {
147 | location = Process.GetCurrentProcess().MainModule?.FileName;
148 | }
149 | catch
150 | {
151 | // Ignore - MainModule can throw in some scenarios
152 | }
153 | }
154 |
155 | // Fallback 3: AppDomain.BaseDirectory
156 | if (string.IsNullOrEmpty(location))
157 | {
158 | location = AppDomain.CurrentDomain.BaseDirectory;
159 | // AppDomain.BaseDirectory already returns a directory, not a file
160 | return location?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
161 | }
162 |
163 | return !string.IsNullOrEmpty(location) ? Path.GetDirectoryName(location) : null;
164 | }
165 | }
166 | ///
167 | /// Returns the file path of the application
168 | /// Handles single-file publish scenarios where Assembly.Location is empty
169 | ///
170 | public static string ExecutablePath
171 | {
172 | get
173 | {
174 | // Try Assembly.Location first
175 | string location = Assembly.GetExecutingAssembly().Location;
176 |
177 | // Fallback 1: Environment.ProcessPath (available in .NET 6+)
178 | if (string.IsNullOrEmpty(location))
179 | {
180 | location = Environment.ProcessPath;
181 | }
182 |
183 | // Fallback 2: Process.MainModule.FileName
184 | if (string.IsNullOrEmpty(location))
185 | {
186 | try
187 | {
188 | location = Process.GetCurrentProcess().MainModule?.FileName;
189 | }
190 | catch
191 | {
192 | // Ignore - MainModule can throw in some scenarios
193 | }
194 | }
195 |
196 | // Fallback 3: Construct from AppDomain.BaseDirectory + assembly name
197 | if (string.IsNullOrEmpty(location))
198 | {
199 | string baseDir = AppDomain.CurrentDomain.BaseDirectory;
200 | string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
201 | location = Path.Combine(baseDir, assemblyName + ".exe");
202 | }
203 |
204 | return location;
205 | }
206 | }
207 | #endregion
208 |
209 | #region MahApps Style
210 | ///
211 | /// Theme Light/Dark enum
212 | ///
213 | public enum Themes
214 | {
215 | Light,
216 | Dark
217 | }
218 | ///
219 | /// All accent colors in one enum
220 | ///
221 | public enum Accents
222 | {
223 | Red,
224 | Green,
225 | Blue,
226 | Purple,
227 | Orange,
228 | Lime,
229 | Emerald,
230 | Teal,
231 | Cyan,
232 | Cobalt,
233 | Indigo,
234 | Violet,
235 | Pink,
236 | Magenta,
237 | Crimson,
238 | Amber,
239 | Yellow,
240 | Brown,
241 | Olive,
242 | Steel,
243 | Mauve,
244 | Taupe,
245 | Sienna
246 | }
247 | #endregion
248 | }
249 | }
250 |
--------------------------------------------------------------------------------
/RunAsAdmin/Views/LogViewerWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using LiteDB;
2 | using MahApps.Metro.Controls;
3 | using Serilog.Events;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.ComponentModel;
7 | using System.Data;
8 | using System.IO;
9 | using System.Linq;
10 | using System.Reflection;
11 | using System.Threading.Tasks;
12 | using System.Windows;
13 | using System.Windows.Controls;
14 | using System.Windows.Input;
15 |
16 | namespace RunAsAdmin.Views
17 | {
18 | ///
19 | /// Interaktionslogik für LogViewerWindow.xaml
20 | ///
21 | public partial class LogViewerWindow : MetroWindow
22 | {
23 |
24 | // TODO: Finish the LogViewer and Update to v2.0.
25 | public LogViewerWindow()
26 | {
27 | InitializeComponent();
28 | }
29 |
30 | #region Logfile names and paths
31 | private static List GetAllLogFileNames()
32 | {
33 | var list = new List();
34 | try
35 | {
36 | if (Directory.Exists(GlobalVars.PublicDocumentsWithAssemblyName))
37 | {
38 | var fileNames = Directory.GetFiles(GlobalVars.PublicDocumentsWithAssemblyName, "Logger*.db").Select(Path.GetFileName).ToList();
39 | foreach (var fileName in fileNames)
40 | {
41 | list.Add(fileName);
42 | }
43 | return list;
44 | }
45 | throw new DirectoryNotFoundException();
46 | }
47 | catch (Exception ex)
48 | {
49 | GlobalVars.Loggi.Error(ex, ex.Message);
50 | return null;
51 | }
52 | }
53 | private static List GetAllLogFilePaths()
54 | {
55 | var list = new List();
56 | try
57 | {
58 | var filePaths = Directory.GetFiles(GlobalVars.PublicDocumentsWithAssemblyName, "Logger*.db").ToList();
59 | foreach (var filePath in filePaths)
60 | {
61 | list.Add(filePath);
62 | }
63 | return list;
64 | }
65 | catch (Exception ex)
66 | {
67 | GlobalVars.Loggi.Error(ex, ex.Message);
68 | return null;
69 | }
70 | }
71 | #endregion
72 |
73 | private void MetroWindow_ContentRendered(object sender, EventArgs e)
74 | {
75 | SelectLogFileComboBox.SelectionChanged -= SelectLogFileComboBox_SelectionChanged;
76 | SelectLogFileComboBox.ItemsSource = GetAllLogFileNames();
77 | SelectLogFileComboBox.SelectedItem = Path.GetFileName(GlobalVars.LoggerPath);
78 | SelectLogFileComboBox.SelectionChanged += SelectLogFileComboBox_SelectionChanged;
79 | LoadLogData();
80 | }
81 |
82 | private async Task> GetLogDataAsync()
83 | {
84 | var logModels = new List();
85 | string conString = $"Filename={GlobalVars.PublicDocumentsWithAssemblyName}\\{SelectLogFileComboBox.SelectedItem};ReadOnly=true";
86 | var result = await Task.Run(() =>
87 | {
88 | using var db = new LiteDatabase(conString);
89 | var Items = db.GetCollection("log");
90 | foreach (LogModel Item in Items.FindAll())
91 | {
92 | logModels.Add(Item);
93 | }
94 | var sortedLogModels = logModels.OrderByDescending(d => d._t.TimeOfDay).ToList();
95 | return sortedLogModels;
96 | });
97 | return result;
98 | }
99 |
100 | public async void LoadLogData()
101 | {
102 | try
103 | {
104 | Mouse.OverrideCursor = Cursors.Wait;
105 | // Load the LogModel Data
106 | LoggerDataGridView.ItemsSource = await GetLogDataAsync();
107 | // All column headers are overwritten with the DisplayName value of the property
108 | LogModel lm = new LogModel();
109 | var props = lm.GetType().GetProperties();
110 | for (int i = 0; i < props.Count(); i++)
111 | {
112 | LoggerDataGridView.Columns[i].Header = props[i].GetCustomAttribute()?.DisplayName;
113 | }
114 | }
115 | catch (Exception ex)
116 | {
117 | GlobalVars.Loggi.Error(ex, ex.Message);
118 | }
119 | finally
120 | {
121 | Mouse.OverrideCursor = null;
122 | }
123 | }
124 |
125 | private void LoggerDataGridView_LoadingRow(object sender, DataGridRowEventArgs e)
126 | {
127 | LogModel RowDataContaxt = e.Row.DataContext as LogModel;
128 | if (RowDataContaxt != null)
129 | {
130 | //Verbose - Is a computer logging mode that records more information than the usual logging mode. (Verbose means "using more words than necessary".)
131 | //Debug - Information that is diagnostically helpful to people more than just developers(IT, sysadmins, etc.).
132 | //Info - Generally useful information to log(service start/ stop, configuration assumptions, etc). Info I want to always have available but usually don't care about under normal circumstances. This is my out-of-the-box config level.
133 | //Warn - Anything that can potentially cause application oddities, but for which I am automatically recovering. (Such as switching from a primary to backup server, retrying an operation, missing secondary data, etc.)
134 | //Error - Any error which is fatal to the operation, but not the service or application(can't open a required file, missing data, etc.). These errors will force user (administrator, or direct user) intervention. These are usually reserved (in my apps) for incorrect connection strings, missing services, etc.
135 | //Fatal - Any error that is forcing a shutdown of the service or application to prevent data loss(or further data loss).I reserve these only for the most heinous errors and situations where there is guaranteed to have been data corruption or loss.
136 | e.Row.BorderThickness = new Thickness(10, 0, 0, 0);
137 | switch (Enum.Parse(typeof(LogEventLevel), RowDataContaxt._l))
138 | {
139 | case LogEventLevel.Verbose:
140 | e.Row.BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
141 | break;
142 | case LogEventLevel.Debug:
143 | e.Row.BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 255));
144 | break;
145 | case LogEventLevel.Information:
146 | e.Row.BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 255, 0));
147 | break;
148 | case LogEventLevel.Warning:
149 | e.Row.BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 0));
150 | break;
151 | case LogEventLevel.Error:
152 | e.Row.BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 0, 0));
153 | break;
154 | case LogEventLevel.Fatal:
155 | e.Row.BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 128, 0));
156 | break;
157 | default:
158 | e.Row.BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 0));
159 | break;
160 | }
161 | }
162 | }
163 |
164 | private void DeleteLogFileButton_Click(object sender, RoutedEventArgs e)
165 | {
166 | try
167 | {
168 | if (SelectLogFileComboBox.SelectedItem != null && SelectLogFileComboBox.Items.Count > 1 && SelectLogFileComboBox.SelectedItem.ToString() != Path.GetFileName(GlobalVars.LoggerPath))
169 | {
170 | var file = GetAllLogFilePaths().FirstOrDefault(s => s.Contains(SelectLogFileComboBox.SelectedItem.ToString()));
171 | if (File.Exists(file))
172 | {
173 | if (file != null) File.Delete(file);
174 | }
175 | SelectLogFileComboBox.SelectedItem = Path.GetFileName(GlobalVars.LoggerPath);
176 | SelectLogFileComboBox.ItemsSource = GetAllLogFileNames();
177 | }
178 | }
179 | catch (Exception ex)
180 | {
181 | GlobalVars.Loggi.Error(ex, ex.Message);
182 | }
183 | }
184 | private void SelectLogFileComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
185 | {
186 | LoadLogData();
187 | }
188 |
189 | private void RefreshButton_Click(object sender, RoutedEventArgs e)
190 | {
191 | LoadLogData();
192 | }
193 |
194 | public class LogModel
195 | {
196 | //[DisplayName("Log ID")]
197 | //public ObjectId _id { get; set; }
198 | [DisplayName("Date and Time")]
199 | public DateTime _t { get; set; }
200 | //[DisplayName("Year")]
201 | //public int _ty { get; set; }
202 | //[DisplayName("Month")]
203 | //public int _tm { get; set; }
204 | //[DisplayName("Day")]
205 | //public int _td { get; set; }
206 | //[DisplayName("Week")]
207 | //public int _tw { get; set; }
208 | [DisplayName("Log Message")]
209 | public string _m { get; set; }
210 | //[DisplayName("Message")]
211 | //public string _mt { get; set; }
212 | [DisplayName("ID")]
213 | public string _i { get; set; }
214 | [DisplayName("Log Level")]
215 | public string _l { get; set; }
216 | [DisplayName("Error Message")]
217 | public string _x { get; set; }
218 | }
219 | }
220 | }
221 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Automated Release
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | - master
8 | paths-ignore:
9 | - '**.md'
10 | - '.github/workflows/ci.yml'
11 | - 'docs/**'
12 | workflow_dispatch:
13 | inputs:
14 | force_release:
15 | description: 'Force release even if version unchanged'
16 | required: false
17 | type: boolean
18 | default: false
19 | skip_version_check:
20 | description: 'Skip version validation (use with caution)'
21 | required: false
22 | type: boolean
23 | default: false
24 |
25 | jobs:
26 | check-version:
27 | name: Check Version
28 | runs-on: ubuntu-latest
29 | outputs:
30 | should_release: ${{ steps.version_check.outputs.should_release }}
31 | current_version: ${{ steps.version_check.outputs.current_version }}
32 | latest_version: ${{ steps.version_check.outputs.latest_version }}
33 | release_version: ${{ steps.version_check.outputs.release_version }}
34 | version_changed: ${{ steps.version_check.outputs.version_changed }}
35 |
36 | steps:
37 | - name: Checkout Code
38 | uses: actions/checkout@v4
39 | with:
40 | fetch-depth: 0
41 | ref: ${{ github.sha }}
42 |
43 | - name: Debug - Show Checkout Info
44 | shell: pwsh
45 | run: |
46 | Write-Host "========================================" -ForegroundColor Cyan
47 | Write-Host "Checkout Information" -ForegroundColor Cyan
48 | Write-Host "========================================" -ForegroundColor Cyan
49 | Write-Host "GitHub SHA: ${{ github.sha }}" -ForegroundColor Yellow
50 | Write-Host "GitHub Ref: ${{ github.ref }}" -ForegroundColor Yellow
51 | Write-Host "GitHub Event: ${{ github.event_name }}" -ForegroundColor Yellow
52 | Write-Host "Working Directory: $(Get-Location)" -ForegroundColor Yellow
53 |
54 | if (Test-Path "RunAsAdmin/Properties/AssemblyInfo.cs") {
55 | Write-Host "✓ AssemblyInfo.cs exists" -ForegroundColor Green
56 | $content = Get-Content "RunAsAdmin/Properties/AssemblyInfo.cs" -Raw
57 | if ($content -match '\[assembly:\s*AssemblyVersion\s*\(\s*"([^"]+)"\s*\)\]') {
58 | Write-Host " Version found: $($matches[1])" -ForegroundColor Green
59 | }
60 | } else {
61 | Write-Host "✗ AssemblyInfo.cs NOT FOUND" -ForegroundColor Red
62 | }
63 | Write-Host "========================================" -ForegroundColor Cyan
64 |
65 | - name: Run Version Check
66 | id: version_check
67 | shell: pwsh
68 | env:
69 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
70 | run: |
71 | $scriptPath = ".github/scripts/check-version.ps1"
72 | $assemblyInfoPath = "RunAsAdmin/Properties/AssemblyInfo.cs"
73 | $repo = "${{ github.repository }}"
74 |
75 | & $scriptPath -AssemblyInfoPath $assemblyInfoPath -GitHubRepo $repo -GitHubToken $env:GITHUB_TOKEN
76 |
77 | - name: Apply Manual Overrides
78 | if: github.event_name == 'workflow_dispatch'
79 | id: override_check
80 | shell: pwsh
81 | run: |
82 | $shouldRelease = "${{ steps.version_check.outputs.should_release }}"
83 | $forceRelease = "${{ github.event.inputs.force_release }}"
84 |
85 | if ($forceRelease -eq "true") {
86 | Write-Host "Force release enabled - overriding version check" -ForegroundColor Yellow
87 | echo "should_release=true" >> $env:GITHUB_OUTPUT
88 | } else {
89 | echo "should_release=$shouldRelease" >> $env:GITHUB_OUTPUT
90 | }
91 |
92 | - name: Version Check Summary
93 | shell: pwsh
94 | run: |
95 | Write-Host ""
96 | Write-Host "========================================" -ForegroundColor Cyan
97 | Write-Host "Version Check Summary" -ForegroundColor Cyan
98 | Write-Host "========================================" -ForegroundColor Cyan
99 | Write-Host "Current Version: ${{ steps.version_check.outputs.current_version }}" -ForegroundColor Yellow
100 | Write-Host "Latest Release: ${{ steps.version_check.outputs.latest_version }}" -ForegroundColor Yellow
101 | Write-Host "Should Release: ${{ steps.version_check.outputs.should_release }}" -ForegroundColor Yellow
102 | Write-Host "Release Version: ${{ steps.version_check.outputs.release_version }}" -ForegroundColor Yellow
103 | Write-Host "========================================" -ForegroundColor Cyan
104 |
105 | build-and-release:
106 | name: Build and Release
107 | needs: check-version
108 | if: needs.check-version.outputs.should_release == 'true' || github.event.inputs.force_release == 'true'
109 | runs-on: windows-latest
110 | permissions:
111 | contents: write
112 |
113 | steps:
114 | - name: Checkout Code
115 | uses: actions/checkout@v4
116 | with:
117 | fetch-depth: 0
118 | ref: ${{ github.sha }}
119 |
120 | - name: Setup .NET 8
121 | uses: actions/setup-dotnet@v4
122 | with:
123 | dotnet-version: '8.0.x'
124 |
125 | - name: Display Release Information
126 | shell: pwsh
127 | run: |
128 | Write-Host "========================================" -ForegroundColor Cyan
129 | Write-Host "Release Build Information" -ForegroundColor Cyan
130 | Write-Host "========================================" -ForegroundColor Cyan
131 | Write-Host "Repository: ${{ github.repository }}" -ForegroundColor Yellow
132 | Write-Host "Branch: ${{ github.ref_name }}" -ForegroundColor Yellow
133 | Write-Host "Commit: ${{ github.sha }}" -ForegroundColor Yellow
134 | Write-Host "Release Version: ${{ needs.check-version.outputs.release_version }}" -ForegroundColor Green
135 | Write-Host "Event Type: ${{ github.event_name }}" -ForegroundColor Yellow
136 | Write-Host ".NET Version: $(dotnet --version)" -ForegroundColor Yellow
137 | Write-Host "========================================" -ForegroundColor Cyan
138 |
139 | - name: Restore Dependencies
140 | run: dotnet restore RunAsAdmin/RunAsAdmin.csproj
141 |
142 | - name: Publish Single-File Release
143 | run: dotnet publish RunAsAdmin/RunAsAdmin.csproj -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=None -p:DebugSymbols=false
144 |
145 | - name: Create Release Package
146 | id: create_package
147 | shell: pwsh
148 | run: |
149 | Write-Host "Creating release package..." -ForegroundColor Yellow
150 |
151 | $publishPath = "RunAsAdmin\bin\Release\net8.0-windows\win-x64\publish"
152 | $releaseExe = Join-Path $publishPath "RunAsAdmin.exe"
153 | $releaseZip = "RunAsAdmin.zip"
154 |
155 | # Verify publish directory exists
156 | if (-not (Test-Path $publishPath)) {
157 | Write-Host "✗ Publish directory not found: $publishPath" -ForegroundColor Red
158 | exit 1
159 | }
160 |
161 | # Check for single-file EXE
162 | if (-not (Test-Path $releaseExe)) {
163 | Write-Host "✗ Single-file executable not found: $releaseExe" -ForegroundColor Red
164 | Write-Host "Contents of publish directory:" -ForegroundColor Yellow
165 | Get-ChildItem $publishPath | ForEach-Object { Write-Host " - $($_.Name)" }
166 | exit 1
167 | }
168 |
169 | $exeSize = (Get-Item $releaseExe).Length
170 | $exeSizeMB = [math]::Round($exeSize / 1MB, 2)
171 | Write-Host "✓ Single-file executable found: $releaseExe ($exeSizeMB MB)" -ForegroundColor Green
172 |
173 | # Verify it's truly a single file (no DLLs should be present)
174 | $dllCount = (Get-ChildItem $publishPath -Filter "*.dll" | Measure-Object).Count
175 | if ($dllCount -gt 0) {
176 | Write-Host "⚠ Warning: Found $dllCount DLL files in publish directory" -ForegroundColor Yellow
177 | Write-Host "This may indicate single-file publishing did not work correctly" -ForegroundColor Yellow
178 | } else {
179 | Write-Host "✓ No DLL files found - single-file packaging successful!" -ForegroundColor Green
180 | }
181 |
182 | # Create ZIP with only the EXE
183 | Write-Host "Creating ZIP package..." -ForegroundColor Yellow
184 | Compress-Archive -Path $releaseExe -DestinationPath $releaseZip -Force
185 |
186 | if (-not (Test-Path $releaseZip)) {
187 | Write-Host "✗ Failed to create ZIP file" -ForegroundColor Red
188 | exit 1
189 | }
190 |
191 | $zipSize = (Get-Item $releaseZip).Length
192 | $zipSizeMB = [math]::Round($zipSize / 1MB, 2)
193 | Write-Host "✓ Release ZIP ready: $releaseZip ($zipSizeMB MB)" -ForegroundColor Green
194 |
195 | echo "zip_path=$releaseZip" >> $env:GITHUB_OUTPUT
196 | echo "zip_size=$zipSize" >> $env:GITHUB_OUTPUT
197 | echo "exe_size=$exeSize" >> $env:GITHUB_OUTPUT
198 |
199 | - name: Create Git Tag
200 | shell: pwsh
201 | env:
202 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
203 | run: |
204 | $version = "${{ needs.check-version.outputs.release_version }}"
205 |
206 | Write-Host "Creating Git tag: $version" -ForegroundColor Yellow
207 |
208 | git config user.name "github-actions[bot]"
209 | git config user.email "github-actions[bot]@users.noreply.github.com"
210 |
211 | # Check if tag already exists
212 | $tagExists = git tag -l $version
213 |
214 | if ($tagExists) {
215 | Write-Host "⚠ Tag $version already exists - skipping tag creation" -ForegroundColor Yellow
216 | } else {
217 | git tag -a $version -m "Release $version"
218 | git push origin $version
219 | Write-Host "✓ Tag $version created and pushed" -ForegroundColor Green
220 | }
221 |
222 | - name: Create GitHub Release
223 | uses: softprops/action-gh-release@v2
224 | with:
225 | tag_name: ${{ needs.check-version.outputs.release_version }}
226 | name: Release ${{ needs.check-version.outputs.release_version }}
227 | generate_release_notes: true
228 | files: |
229 | RunAsAdmin.zip
230 | draft: false
231 | prerelease: false
232 | token: ${{ secrets.GITHUB_TOKEN }}
233 | fail_on_unmatched_files: true
234 | env:
235 | GITHUB_REPOSITORY: ${{ github.repository }}
236 |
237 | - name: Release Summary
238 | if: success()
239 | shell: pwsh
240 | run: |
241 | $version = "${{ needs.check-version.outputs.release_version }}"
242 | $repo = "${{ github.repository }}"
243 |
244 | Write-Host ""
245 | Write-Host "========================================" -ForegroundColor Cyan
246 | Write-Host "Release Created Successfully!" -ForegroundColor Green
247 | Write-Host "========================================" -ForegroundColor Cyan
248 | Write-Host "Version: $version" -ForegroundColor Yellow
249 | Write-Host "URL: https://github.com/$repo/releases/tag/$version" -ForegroundColor Yellow
250 | Write-Host "========================================" -ForegroundColor Cyan
251 |
252 | - name: Upload Build Artifacts (for debugging)
253 | if: always()
254 | uses: actions/upload-artifact@v4
255 | with:
256 | name: release-artifacts-${{ needs.check-version.outputs.current_version }}
257 | path: |
258 | RunAsAdmin.zip
259 | RunAsAdmin/bin/Release/net8.0-windows/win-x64/publish/RunAsAdmin.exe
260 | retention-days: 30
261 | if-no-files-found: warn
262 |
--------------------------------------------------------------------------------
/RunAsAdmin/Core/Helper.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Win32;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Diagnostics;
5 | using System.DirectoryServices;
6 | using System.DirectoryServices.AccountManagement;
7 | using System.DirectoryServices.ActiveDirectory;
8 | using System.Drawing;
9 | using System.IO;
10 | using System.Linq;
11 | using System.Runtime.InteropServices;
12 | using System.Security;
13 | using System.Security.AccessControl;
14 | using System.Security.Principal;
15 | using System.Threading;
16 | using System.Threading.Tasks;
17 | using System.Windows.Forms;
18 |
19 | namespace RunAsAdmin.Core
20 | {
21 | public static class Helper
22 | {
23 | #region Bind textbox custom source
24 | public static void SetDataSource(System.Windows.Controls.ComboBox comboBox, params string[] stringArray)
25 | {
26 | try
27 | {
28 | if (comboBox == null)
29 | {
30 | GlobalVars.Loggi.Error("SetDataSource called with null comboBox");
31 | throw new ArgumentNullException(nameof(comboBox));
32 | }
33 |
34 | if (stringArray != null && stringArray.Length > 0)
35 | {
36 | Array.Sort(stringArray);
37 | AutoCompleteStringCollection col = new AutoCompleteStringCollection();
38 | foreach (var item in stringArray)
39 | {
40 | if (!string.IsNullOrWhiteSpace(item))
41 | {
42 | col.Add(item);
43 | }
44 | }
45 | comboBox.ItemsSource = col;
46 | GlobalVars.Loggi.Debug("Successfully set data source with {Count} items", col.Count);
47 | }
48 | else
49 | {
50 | GlobalVars.Loggi.Warning("SetDataSource called with null or empty stringArray");
51 | comboBox.ItemsSource = null;
52 | }
53 | }
54 | catch (Exception ex)
55 | {
56 | GlobalVars.Loggi.Error(ex, "Error setting data source for comboBox");
57 | throw;
58 | }
59 | }
60 | #endregion
61 |
62 | #region Get all Domains as string list
63 | public static List GetAllDomains()
64 | {
65 | var domainList = new List();
66 | try
67 | {
68 | domainList.Add(Environment.MachineName);
69 |
70 | // Try to get system domain
71 | try
72 | {
73 | string systemDomain = Environment.UserDomainName;
74 | if (!string.IsNullOrEmpty(systemDomain) &&
75 | !systemDomain.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase) &&
76 | !domainList.Contains(systemDomain))
77 | {
78 | domainList.Add(systemDomain);
79 | GlobalVars.Loggi.Debug("Added system domain: {Domain}", systemDomain);
80 | }
81 | }
82 | catch (Exception domainEx)
83 | {
84 | GlobalVars.Loggi.Debug(domainEx, "Could not retrieve system domain");
85 | }
86 |
87 | using var forest = Forest.GetCurrentForest();
88 | foreach (Domain domain in forest.Domains)
89 | {
90 | if (!domainList.Contains(domain.Name))
91 | {
92 | domainList.Add(domain.Name);
93 | }
94 | domain.Dispose();
95 | }
96 | GlobalVars.Loggi.Debug("Successfully retrieved {Count} domains", domainList.Count);
97 | return domainList;
98 | }
99 | catch (ActiveDirectoryObjectNotFoundException adEx)
100 | {
101 | GlobalVars.Loggi.Warning(adEx, "Active Directory not available, returning available domains");
102 | return domainList;
103 | }
104 | catch (ActiveDirectoryOperationException adOpEx)
105 | {
106 | GlobalVars.Loggi.Warning(adOpEx, "Not associated with Active Directory domain or forest, returning available domains");
107 | return domainList;
108 | }
109 | catch (Exception ex)
110 | {
111 | GlobalVars.Loggi.Error(ex, "Error retrieving domain list, returning available domains");
112 | return domainList;
113 | }
114 | }
115 | #endregion
116 |
117 | #region Get all local users as string list
118 | private const int UF_ACCOUNTDISABLE = 0x0002;
119 | public static List GetLocalUsers()
120 | {
121 | var users = new List();
122 | try
123 | {
124 | var path = string.Format("WinNT://{0},computer", Environment.MachineName);
125 | using var computerEntry = new DirectoryEntry(path);
126 | foreach (DirectoryEntry childEntry in computerEntry.Children)
127 | {
128 | if (childEntry.SchemaClassName == "User")// filter all users
129 | {
130 | if (((int)childEntry.Properties["UserFlags"].Value & UF_ACCOUNTDISABLE) != UF_ACCOUNTDISABLE)// only if accounts are enabled
131 | {
132 | users.Add(childEntry.Name); // add active user to list
133 | }
134 | }
135 | childEntry.Dispose(); // Dispose each child entry
136 | }
137 | GlobalVars.Loggi.Debug("Successfully retrieved {Count} local users", users.Count);
138 | return users;
139 | }
140 | catch (UnauthorizedAccessException uaEx)
141 | {
142 | GlobalVars.Loggi.Warning(uaEx, "Access denied when retrieving local users");
143 | return users;
144 | }
145 | catch (Exception ex)
146 | {
147 | GlobalVars.Loggi.Error(ex, "Error retrieving local users");
148 | return users;
149 | }
150 | }
151 | #endregion
152 |
153 | #region Get all ad users as string list
154 | public static List GetADUsers()
155 | {
156 | var ADUsers = new List();
157 | try
158 | {
159 | using var forest = Forest.GetCurrentForest();
160 | foreach (Domain domain in forest.Domains)
161 | {
162 | using (var context = new PrincipalContext(ContextType.Domain, domain.Name))
163 | {
164 | using var searcher = new PrincipalSearcher(new UserPrincipal(context));
165 | foreach (var result in searcher.FindAll())
166 | {
167 | using (result)
168 | {
169 | DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
170 | if (de?.Properties["samAccountName"]?.Value != null)
171 | {
172 | ADUsers.Add(de.Properties["samAccountName"].Value.ToString());
173 | }
174 | }
175 | }
176 | }
177 | domain.Dispose();
178 | }
179 | GlobalVars.Loggi.Debug("Successfully retrieved {Count} AD users", ADUsers.Count);
180 | return ADUsers;
181 | }
182 | catch (ActiveDirectoryObjectNotFoundException adEx)
183 | {
184 | GlobalVars.Loggi.Warning(adEx, "Active Directory not available");
185 | return ADUsers;
186 | }
187 | catch (ActiveDirectoryOperationException adOpEx)
188 | {
189 | GlobalVars.Loggi.Warning(adOpEx, "Not associated with Active Directory domain or forest");
190 | return ADUsers;
191 | }
192 | catch (PrincipalServerDownException psEx)
193 | {
194 | GlobalVars.Loggi.Warning(psEx, "Domain controller is not available");
195 | return ADUsers;
196 | }
197 | catch (Exception ex)
198 | {
199 | GlobalVars.Loggi.Error(ex, "Error retrieving AD users");
200 | return ADUsers;
201 | }
202 | }
203 | #endregion
204 |
205 | #region Get cached AD users from local profiles
206 | ///
207 | /// Gets AD users that have logged into this machine and have local profiles
208 | /// This works even when AD is not accessible
209 | ///
210 | public static List GetCachedADUsers()
211 | {
212 | var cachedUsers = new List();
213 | try
214 | {
215 | // Open the ProfileList registry key
216 | using (var profileListKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"))
217 | {
218 | if (profileListKey != null)
219 | {
220 | foreach (string sidString in profileListKey.GetSubKeyNames())
221 | {
222 | try
223 | {
224 | // Try to convert SID string to SecurityIdentifier
225 | if (sidString.StartsWith("S-1-5-21-")) // Domain user SID pattern
226 | {
227 | var sid = new SecurityIdentifier(sidString);
228 |
229 | // Try to translate SID to account name
230 | try
231 | {
232 | var account = sid.Translate(typeof(NTAccount)) as NTAccount;
233 | if (account != null)
234 | {
235 | string accountName = account.Value;
236 | // Extract username from DOMAIN\Username format
237 | if (accountName.Contains("\\"))
238 | {
239 | string username = accountName.Split('\\')[1];
240 | if (!cachedUsers.Contains(username))
241 | {
242 | cachedUsers.Add(username);
243 | }
244 | }
245 | }
246 | }
247 | catch (IdentityNotMappedException)
248 | {
249 | // SID cannot be resolved (user might be deleted from AD)
250 | GlobalVars.Loggi.Debug("Could not resolve SID: {SID}", sidString);
251 | }
252 | }
253 | }
254 | catch (Exception sidEx)
255 | {
256 | GlobalVars.Loggi.Debug(sidEx, "Error processing SID: {SID}", sidString);
257 | }
258 | }
259 | }
260 | }
261 |
262 | GlobalVars.Loggi.Debug("Successfully retrieved {Count} cached AD users from profiles", cachedUsers.Count);
263 | return cachedUsers;
264 | }
265 | catch (SecurityException secEx)
266 | {
267 | GlobalVars.Loggi.Warning(secEx, "Insufficient permissions to read user profiles");
268 | return cachedUsers;
269 | }
270 | catch (UnauthorizedAccessException uaEx)
271 | {
272 | GlobalVars.Loggi.Warning(uaEx, "Access denied when reading user profiles");
273 | return cachedUsers;
274 | }
275 | catch (Exception ex)
276 | {
277 | GlobalVars.Loggi.Error(ex, "Error retrieving cached AD users");
278 | return cachedUsers;
279 | }
280 | }
281 | #endregion
282 |
283 | #region Get all users (AD + Local + Cached)
284 | public static List GetAllUsers()
285 | {
286 | var allUsers = new List();
287 | try
288 | {
289 | // Get local users first
290 | var localUsers = GetLocalUsers();
291 | foreach (var user in localUsers)
292 | {
293 | if (!allUsers.Contains(user))
294 | {
295 | allUsers.Add(user);
296 | }
297 | }
298 |
299 | // Try to get AD users from directory
300 | var adUsers = GetADUsers();
301 | foreach (var user in adUsers)
302 | {
303 | if (!allUsers.Contains(user))
304 | {
305 | allUsers.Add(user);
306 | }
307 | }
308 |
309 | // If AD is not available or returned no users, get cached AD users
310 | if (adUsers.Count == 0)
311 | {
312 | GlobalVars.Loggi.Information("AD users not available, retrieving cached AD users from local profiles");
313 | var cachedUsers = GetCachedADUsers();
314 | foreach (var user in cachedUsers)
315 | {
316 | if (!allUsers.Contains(user))
317 | {
318 | allUsers.Add(user);
319 | }
320 | }
321 | GlobalVars.Loggi.Debug("Successfully retrieved {Count} total users ({LocalCount} local, {CachedCount} cached AD)",
322 | allUsers.Count, localUsers.Count, cachedUsers.Count);
323 | }
324 | else
325 | {
326 | GlobalVars.Loggi.Debug("Successfully retrieved {Count} total users ({LocalCount} local, {ADCount} AD)",
327 | allUsers.Count, localUsers.Count, adUsers.Count);
328 | }
329 |
330 | return allUsers;
331 | }
332 | catch (Exception ex)
333 | {
334 | GlobalVars.Loggi.Error(ex, "Error retrieving all users");
335 | return allUsers;
336 | }
337 | }
338 | #endregion
339 |
340 | #region Uppercase first letter
341 | public static string UppercaseFirst(string str)
342 | {
343 | if (string.IsNullOrEmpty(str))
344 | return string.Empty;
345 | return char.ToUpper(str[0]) + str.Substring(1).ToLower();
346 | }
347 | #endregion
348 |
349 | #region Get users SID
350 | public static string GetUsersSID()
351 | {
352 | try
353 | {
354 | // create your domain context
355 | using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
356 | {
357 | // find the user
358 | using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, WindowsIdentity.GetCurrent().Name))
359 | {
360 | if (user != null)
361 | {
362 | var usersSid = user.Sid.ToString();
363 | var username = user.DisplayName;
364 | var userSamAccountName = user.SamAccountName;
365 | GlobalVars.Loggi.Debug("Successfully retrieved SID for user: {Username}", username);
366 | return usersSid;
367 | }
368 |
369 | GlobalVars.Loggi.Warning("User not found in domain context for: {CurrentUser}", WindowsIdentity.GetCurrent().Name);
370 | return null;
371 | }
372 | }
373 | }
374 | catch (PrincipalServerDownException psEx)
375 | {
376 | GlobalVars.Loggi.Error(psEx, "Domain controller is not available");
377 | return null;
378 | }
379 | catch (Exception ex)
380 | {
381 | GlobalVars.Loggi.Error(ex, "Error retrieving user SID for: {CurrentUser}", WindowsIdentity.GetCurrent().Name);
382 | return null;
383 | }
384 | }
385 | #endregion
386 |
387 | #region SecureString Helper
388 | public static SecureString GetSecureString(string password)
389 | {
390 | if (password == null)
391 | throw new ArgumentNullException("password is invalid or null");
392 |
393 | var securePassword = new SecureString();
394 |
395 | foreach (char c in password)
396 | securePassword.AppendChar(c);
397 |
398 | securePassword.MakeReadOnly();
399 | return securePassword;
400 | }
401 |
402 | public static string SecureStringToString(SecureString value)
403 | {
404 | IntPtr valuePtr = IntPtr.Zero;
405 | try
406 | {
407 | valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
408 | return Marshal.PtrToStringUni(valuePtr);
409 | }
410 | finally
411 | {
412 | Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
413 | }
414 | }
415 | #endregion
416 |
417 | #region Get current user direcetory
418 | public static string GetUserDirectoryPath()
419 | {
420 | string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
421 | if (Environment.OSVersion.Version.Major >= 6)
422 | {
423 | path = Directory.GetParent(path).ToString();
424 | return path;
425 | }
426 | return path;
427 | }
428 | #endregion
429 | }
430 | }
--------------------------------------------------------------------------------
/RunAsAdmin/Views/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using ControlzEx.Theming;
2 | using MahApps.Metro.Controls;
3 | using MahApps.Metro.Controls.Dialogs;
4 | using MahApps.Metro.IconPacks;
5 | using Onova;
6 | using Onova.Services;
7 | using SimpleImpersonation;
8 | using System;
9 | using System.ComponentModel;
10 | using System.Diagnostics;
11 | using System.IO;
12 | using System.Net.Http;
13 | using System.Reflection;
14 | using System.Security.Principal;
15 | using System.Threading;
16 | using System.Threading.Tasks;
17 | using System.Windows;
18 | using System.Windows.Input;
19 | using Trinet.Core.IO.Ntfs;
20 |
21 | namespace RunAsAdmin.Views
22 | {
23 | ///
24 | /// Interaction logic for MainWindow.xaml
25 | ///
26 | public partial class MainWindow : MetroWindow
27 | {
28 | public MainWindow()
29 | {
30 | InitializeComponent();
31 | GlobalVars.Loggi.Information("Initialize program");
32 | this.Title += $" - v{Assembly.GetExecutingAssembly().GetName().Version.Major}.{Assembly.GetExecutingAssembly().GetName().Version.Minor}.{Assembly.GetExecutingAssembly().GetName().Version.Build}";
33 | InitializeUpdater();
34 | InitializeUserRightInfoLabel();
35 | InitializeDataSource();
36 | }
37 |
38 | #region Windowevents
39 | private void MetroWindow_ContentRendered(object sender, EventArgs e)
40 | {
41 | try
42 | {
43 | InitializeStartUpDetails();
44 | UsernameComboBox.Text = GlobalVars.SettingsHelper.Username ?? string.Empty;
45 | DomainComboBox.Text = GlobalVars.SettingsHelper.Domain ?? string.Empty;
46 | PasswordTextBox.Password = Core.SecurityHelper.Decrypt(GlobalVars.SettingsHelper.Password) ?? string.Empty;
47 | }
48 | catch (Exception ex)
49 | {
50 | GlobalVars.Loggi.Error(ex, ex.Message);
51 | }
52 | }
53 | private void ViewLogMenuItem_Click(object sender, RoutedEventArgs e)
54 | {
55 | LogViewerWindow logViewerWindow = new LogViewerWindow();
56 | logViewerWindow.Show();
57 | }
58 | #endregion
59 |
60 | #region Initialize
61 | public async void InitializeStartUpDetails()
62 | {
63 | try
64 | {
65 | // Get executable path, fallback to process path for single-file publish
66 | string executablePath = GlobalVars.ExecutablePath;
67 | if (string.IsNullOrEmpty(executablePath))
68 | {
69 | executablePath = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName;
70 | GlobalVars.Loggi.Debug("Using process path as fallback for startup check: {Path}", executablePath);
71 | }
72 |
73 | // Validate we have a path before proceeding
74 | if (string.IsNullOrEmpty(executablePath) || !File.Exists(executablePath))
75 | {
76 | GlobalVars.Loggi.Warning("Unable to determine executable path for network drive check");
77 | return;
78 | }
79 |
80 | // Extract root drive path (e.g., "C:\Program Files\App.exe" -> "C:\")
81 | string driveLetter = Path.GetPathRoot(executablePath);
82 | if (string.IsNullOrEmpty(driveLetter))
83 | {
84 | GlobalVars.Loggi.Warning("Unable to determine drive letter from path: {Path}", executablePath);
85 | return;
86 | }
87 |
88 | DriveInfo info = new DriveInfo(driveLetter);
89 | if (info.DriveType == DriveType.Network)
90 | {
91 | await this.ShowMessageAsync("Information at the start", "This program cannot be used from a server path. \nPlease run it from the desktop or a local path!");
92 | }
93 | }
94 | catch (Exception ex)
95 | {
96 | GlobalVars.Loggi.Error(ex, ex.Message);
97 | }
98 | }
99 |
100 | public void InitializeUserRightInfoLabel()
101 | {
102 | try
103 | {
104 | // Get assembly location, fallback to process path for single-file publish
105 | string assemblyLocation = Assembly.GetExecutingAssembly().Location;
106 | if (string.IsNullOrEmpty(assemblyLocation))
107 | {
108 | assemblyLocation = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule?.FileName;
109 | GlobalVars.Loggi.Debug("Using process path as fallback: {Path}", assemblyLocation);
110 | }
111 |
112 | string runLevel = "Unknown";
113 | if (!string.IsNullOrEmpty(assemblyLocation) && File.Exists(assemblyLocation))
114 | {
115 | try
116 | {
117 | runLevel = UACHelper.UACHelper.GetExpectedRunLevel(assemblyLocation).ToString();
118 | }
119 | catch (Exception rlEx)
120 | {
121 | GlobalVars.Loggi.Warning(rlEx, "Could not determine run level for: {Path}", assemblyLocation);
122 | runLevel = "Unable to determine";
123 | }
124 | }
125 |
126 | UserRightsInfoLabel.Content = $"Current user: {Environment.UserName + " - " + WindowsIdentity.GetCurrent().Name}" +
127 | $"\nDefault Behavior: {runLevel}" +
128 | $"\nIs Elevated: {UACHelper.UACHelper.IsElevated}" +
129 | $"\nIs Administrator: {UACHelper.UACHelper.IsAdministrator}" +
130 | $"\nIs Desktop Owner: {UACHelper.UACHelper.IsDesktopOwner}" +
131 | $"\nProcess Owner: {WindowsIdentity.GetCurrent().Name ?? "SYSTEM"}" +
132 | $"\nDesktop Owner: {UACHelper.UACHelper.DesktopOwner}";
133 |
134 | if (!UACHelper.UACHelper.IsAdministrator)
135 | {
136 | StartProgramWithAdminRightsButton.IsEnabled = false;
137 | }
138 | }
139 | catch (Exception ex)
140 | {
141 | GlobalVars.Loggi.Error(ex, ex.Message);
142 | }
143 | }
144 |
145 | public void InitializeDataSource()
146 | {
147 | try
148 | {
149 | Core.Helper.SetDataSource(DomainComboBox, Core.Helper.GetAllDomains().ToArray());
150 | Core.Helper.SetDataSource(UsernameComboBox, Core.Helper.GetAllUsers().ToArray());
151 | }
152 | catch (Exception ex)
153 | {
154 | GlobalVars.Loggi.Error(ex, ex.Message);
155 | }
156 | }
157 |
158 | public void InitializeUpdater()
159 | {
160 | try
161 | {
162 | Task task = Task.Run(async () =>
163 | {
164 | GlobalVars.Loggi.Information("Start Task and check for new update every 5 minutes");
165 | while (true)
166 | {
167 | using (var manager = new UpdateManager(new GithubPackageResolver(GlobalVars.GitHubUsername, GlobalVars.GitHubProjectName, GlobalVars.GitHubAssetName), new ZipPackageExtractor()))
168 | {
169 | var result = await manager.CheckForUpdatesAsync();
170 | if (result.CanUpdate)
171 | {
172 | UpdateBadge.Invoke(new Action(() =>
173 | {
174 | if (this.UpdateBadge.Badge == null)
175 | {
176 | this.UpdateBadge.Badge = new PackIconMaterial() { Kind = PackIconMaterialKind.Update };
177 | }
178 | }));
179 | }
180 | else
181 | {
182 | UpdateBadge.Invoke(new Action(() =>
183 | {
184 | this.UpdateBadge.Badge = null;
185 | }));
186 | }
187 | }
188 | await Task.Delay(300000, UpdateCheckCts.Token);
189 | }
190 | }, UpdateCheckCts.Token);
191 | }
192 | catch (Exception ex)
193 | {
194 | GlobalVars.Loggi.Error(ex, ex.Message);
195 | }
196 | }
197 | #endregion
198 |
199 | #region Update section
200 | private readonly CancellationTokenSource UpdateCheckCts = new CancellationTokenSource();
201 | private async void UpdateButton_Click(object sender, RoutedEventArgs e)
202 | {
203 | try
204 | {
205 | //Configure to look for packages in specified directory and treat them as zips
206 | using var manager = new UpdateManager(new GithubPackageResolver(GlobalVars.GitHubUsername, GlobalVars.GitHubProjectName, GlobalVars.GitHubAssetName), new ZipPackageExtractor());
207 | //Check for updates
208 | var result = await manager.CheckForUpdatesAsync();
209 | GlobalVars.Loggi.Information("Check manually for an update");
210 | if (result.CanUpdate)
211 | {
212 | GlobalVars.Loggi.Information("Can update: {0}", result.CanUpdate);
213 | MessageDialogResult dialogResult = await this.ShowMessageAsync("New update available",
214 | $"A new version is available.\nOld version: " +
215 | $"{Assembly.GetExecutingAssembly().GetName().Version.Major}." +
216 | $"{ Assembly.GetExecutingAssembly().GetName().Version.Minor}." +
217 | $"{ Assembly.GetExecutingAssembly().GetName().Version.Build}" +
218 | $"\nNew version: {result.LastVersion}\nDo you want to update?", MessageDialogStyle.AffirmativeAndNegative);
219 | GlobalVars.Loggi.Information($"Old version: {Assembly.GetExecutingAssembly().GetName().Version}");
220 | GlobalVars.Loggi.Information($"New version: {result.LastVersion}");
221 | if (dialogResult == MessageDialogResult.Affirmative)
222 | {
223 | GlobalVars.Loggi.Information("Start update process");
224 | UpdateWindow updateWindow = new UpdateWindow();
225 | updateWindow.ShowDialog();
226 | }
227 | }
228 | else
229 | {
230 | GlobalVars.Loggi.Information("No update available");
231 | await this.ShowMessageAsync("No update available", "There is currently no update available. Please try again later.", MessageDialogStyle.Affirmative);
232 | }
233 | }
234 | catch (HttpRequestException httpRequestEx)
235 | {
236 | GlobalVars.Loggi.Warning(httpRequestEx.Message);
237 | await this.ShowMessageAsync(httpRequestEx.GetType().Name, httpRequestEx.Message, MessageDialogStyle.Affirmative);
238 | }
239 | catch (Exception ex)
240 | {
241 | GlobalVars.Loggi.Error(ex, ex.Message);
242 | await this.ShowMessageAsync(ex.GetType().Name, ex.Message, MessageDialogStyle.Affirmative);
243 | }
244 | }
245 | #endregion
246 |
247 | #region Settings section
248 | private void SettingsButton_OnClick(object sender, RoutedEventArgs e)
249 | {
250 | SettingsWindow settingsWindow = new SettingsWindow();
251 | settingsWindow.ShowDialog();
252 | }
253 | #endregion
254 |
255 | #region Main Region: Button click events
256 | private async void RestartWithAdminRightsButton_Click(object sender, RoutedEventArgs e)
257 | {
258 | try
259 | {
260 | // Checks if the input is empty
261 | if (String.IsNullOrWhiteSpace((string)DomainComboBox.Text) || String.IsNullOrWhiteSpace((string)UsernameComboBox.Text) || String.IsNullOrWhiteSpace(PasswordTextBox.Password))
262 | {
263 | await this.ShowMessageAsync("Input Required", "Please enter domain, username, and password.");
264 | return;
265 | }
266 |
267 | // Validate ExecutablePath
268 | if (string.IsNullOrEmpty(GlobalVars.ExecutablePath))
269 | {
270 | GlobalVars.Loggi.Error("ExecutablePath is null or empty, cannot restart application");
271 | await this.ShowMessageAsync("Error", "Unable to determine application executable path. Please restart the application manually.");
272 | return;
273 | }
274 |
275 | // Verify executable exists
276 | if (!File.Exists(GlobalVars.ExecutablePath))
277 | {
278 | GlobalVars.Loggi.Error("Executable not found at: {Path}", GlobalVars.ExecutablePath);
279 | await this.ShowMessageAsync("Error", $"Executable not found: {GlobalVars.ExecutablePath}");
280 | return;
281 | }
282 |
283 | Mouse.OverrideCursor = Cursors.Wait;
284 |
285 | // Optional: Add directory security if BasePath is available
286 | // This allows the impersonated user to access the application directory
287 | if (!string.IsNullOrEmpty(GlobalVars.BasePath) && Directory.Exists(GlobalVars.BasePath))
288 | {
289 | try
290 | {
291 | await Task.Run(() =>
292 | {
293 | var credentials = new UserCredentials(GlobalVars.SettingsHelper.Domain, GlobalVars.SettingsHelper.Username, Core.SecurityHelper.Decrypt(GlobalVars.SettingsHelper.Password));
294 | bool hasAccess = false;
295 |
296 | try
297 | {
298 | SimpleImpersonation.Impersonation.RunAsUser(credentials, SimpleImpersonation.LogonType.Interactive, () =>
299 | {
300 | hasAccess = Core.DirectoryHelper.HasDirectoryRights(GlobalVars.BasePath, System.Security.AccessControl.FileSystemRights.ReadAndExecute, winUser: WindowsIdentity.GetCurrent());
301 | });
302 | }
303 | catch (Exception impEx)
304 | {
305 | GlobalVars.Loggi.Warning(impEx, "Could not check directory rights via impersonation");
306 | }
307 |
308 | if (!hasAccess)
309 | {
310 | try
311 | {
312 | Core.DirectoryHelper.AddDirectorySecurity(GlobalVars.BasePath, winUserString: String.Format(@"{0}\{1}", GlobalVars.SettingsHelper.Domain, GlobalVars.SettingsHelper.Username));
313 | GlobalVars.Loggi.Information("Added directory security for user to access application");
314 | }
315 | catch (Exception secEx)
316 | {
317 | GlobalVars.Loggi.Warning(secEx, "Could not add directory security (will attempt to start anyway)");
318 | }
319 | }
320 | });
321 | }
322 | catch (Exception dirSecEx)
323 | {
324 | GlobalVars.Loggi.Warning(dirSecEx, "Directory security check failed (will attempt to start anyway)");
325 | }
326 | }
327 |
328 | // Start the application with new credentials
329 | await Task.Run(() =>
330 | {
331 | try
332 | {
333 | ProcessStartInfo ps = new ProcessStartInfo
334 | {
335 | FileName = GlobalVars.ExecutablePath,
336 | Domain = GlobalVars.SettingsHelper.Domain,
337 | UserName = GlobalVars.SettingsHelper.Username,
338 | Password = Core.Helper.GetSecureString(Core.SecurityHelper.Decrypt(GlobalVars.SettingsHelper.Password)),
339 | LoadUserProfile = true,
340 | UseShellExecute = false,
341 | CreateNoWindow = false,
342 | WindowStyle = ProcessWindowStyle.Normal
343 | };
344 |
345 | GlobalVars.Loggi.Information("Starting application as {Domain}\\{User}", ps.Domain, ps.UserName);
346 |
347 | using (Process p = new Process { StartInfo = ps })
348 | {
349 | if (p.Start())
350 | {
351 | GlobalVars.Loggi.Information("Successfully started new process, exiting current instance");
352 | Application.Current.Dispatcher.Invoke(() => Environment.Exit(0));
353 | }
354 | else
355 | {
356 | GlobalVars.Loggi.Error("Failed to start process");
357 | Application.Current.Dispatcher.Invoke(async () =>
358 | {
359 | await this.ShowMessageAsync("Error", "Failed to start the application with the specified credentials.");
360 | });
361 | }
362 | }
363 | }
364 | catch (Win32Exception win32Ex)
365 | {
366 | GlobalVars.Loggi.Error(win32Ex, "Win32 error starting process: {Message}", win32Ex.Message);
367 | Application.Current.Dispatcher.Invoke(async () =>
368 | {
369 | await this.ShowMessageAsync("Error", $"Failed to start application: {win32Ex.Message}\n\nMake sure the credentials are correct and you have permission to run this application.");
370 | });
371 | }
372 | catch (Exception startEx)
373 | {
374 | GlobalVars.Loggi.Error(startEx, "Error starting process: {Message}", startEx.Message);
375 | Application.Current.Dispatcher.Invoke(async () =>
376 | {
377 | await this.ShowMessageAsync("Error", $"Failed to restart application: {startEx.Message}");
378 | });
379 | }
380 | });
381 | }
382 | catch (Exception ex)
383 | {
384 | GlobalVars.Loggi.Error(ex, "Error in RestartWithAdminRightsButton_Click: {Message}", ex.Message);
385 | await this.ShowMessageAsync("Error", $"An unexpected error occurred: {ex.Message}");
386 | }
387 | finally
388 | {
389 | Mouse.OverrideCursor = null;
390 | }
391 | }
392 |
393 | private async void StartProgramWithAdminRightsButton_Click(object sender, RoutedEventArgs e)
394 | {
395 | try
396 | {
397 | // Checks if the input is empty
398 | if (String.IsNullOrWhiteSpace((string)DomainComboBox.Text) || String.IsNullOrWhiteSpace((string)UsernameComboBox.Text) || String.IsNullOrWhiteSpace(PasswordTextBox.Password))
399 | {
400 | await this.ShowMessageAsync("Input Required", "Please enter domain, username, and password.");
401 | return;
402 | }
403 |
404 | ///Mapped drives are not available from an elevated prompt
405 | ///when UAC is configured to "Prompt for credentials" in Windows
406 | ///https://support.microsoft.com/en-us/help/3035277/mapped-drives-are-not-available-from-an-elevated-prompt-when-uac-is-co#detail%20to%20configure%20the%20registry%20entry
407 | ///https://stackoverflow.com/a/25908932/11189474
408 | System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog
409 | {
410 | Filter = "Application (*.exe)|*.exe|All Files|*.*",
411 | Title = "Select the applications you want to start",
412 | DereferenceLinks = true,
413 | Multiselect = true,
414 | CheckFileExists = true
415 | };
416 |
417 | System.Windows.Forms.DialogResult result = fileDialog.ShowDialog();
418 | if (result == System.Windows.Forms.DialogResult.OK || result == System.Windows.Forms.DialogResult.Yes)
419 | {
420 | string[] paths = fileDialog.FileNames;
421 | int successCount = 0;
422 | int failureCount = 0;
423 |
424 | foreach (var path in paths)
425 | {
426 | try
427 | {
428 | FileInfo file = new FileInfo(path);
429 |
430 | // Remove Zone.Identifier (downloaded from internet mark)
431 | if (file.Exists && file.AlternateDataStreamExists("Zone.Identifier"))
432 | {
433 | try
434 | {
435 | bool deletedIdentifier = file.DeleteAlternateDataStream("Zone.Identifier");
436 | if (deletedIdentifier)
437 | {
438 | GlobalVars.Loggi.Debug("Removed Zone.Identifier from: {Path}", path);
439 | }
440 | }
441 | catch (Exception zoneEx)
442 | {
443 | GlobalVars.Loggi.Warning(zoneEx, "Could not remove Zone.Identifier from: {Path}", path);
444 | }
445 | }
446 |
447 | // Start the application with admin credentials (no UAC prompt)
448 | await Task.Run(() =>
449 | {
450 | try
451 | {
452 | ProcessStartInfo ps = new ProcessStartInfo
453 | {
454 | FileName = path,
455 | Domain = GlobalVars.SettingsHelper.Domain,
456 | UserName = GlobalVars.SettingsHelper.Username,
457 | Password = Core.Helper.GetSecureString(Core.SecurityHelper.Decrypt(GlobalVars.SettingsHelper.Password)),
458 | LoadUserProfile = true,
459 | UseShellExecute = false,
460 | CreateNoWindow = false,
461 | WindowStyle = ProcessWindowStyle.Normal
462 | };
463 |
464 | GlobalVars.Loggi.Information("Starting {Program} as {Domain}\\{User}", Path.GetFileName(path), ps.Domain, ps.UserName);
465 |
466 | using (Process p = new Process { StartInfo = ps })
467 | {
468 | if (p.Start())
469 | {
470 | GlobalVars.Loggi.Information("Successfully started: {Program}", Path.GetFileName(path));
471 | successCount++;
472 | }
473 | else
474 | {
475 | GlobalVars.Loggi.Error("Failed to start: {Program}", Path.GetFileName(path));
476 | failureCount++;
477 | }
478 | }
479 | }
480 | catch (Win32Exception win32ex)
481 | {
482 | GlobalVars.Loggi.Error(win32ex, "Win32 error starting {Program}: {Message}", Path.GetFileName(path), win32ex.Message);
483 | failureCount++;
484 | }
485 | catch (Exception startEx)
486 | {
487 | GlobalVars.Loggi.Error(startEx, "Error starting {Program}: {Message}", Path.GetFileName(path), startEx.Message);
488 | failureCount++;
489 | }
490 | });
491 | }
492 | catch (Exception fileEx)
493 | {
494 | GlobalVars.Loggi.Error(fileEx, "Error processing file: {Path}", path);
495 | failureCount++;
496 | }
497 | }
498 |
499 | // Show summary
500 | if (successCount > 0 || failureCount > 0)
501 | {
502 | string message = $"Started: {successCount} program(s)";
503 | if (failureCount > 0)
504 | {
505 | message += $"\nFailed: {failureCount} program(s)";
506 | }
507 | await this.ShowMessageAsync("Program Start Summary", message);
508 | }
509 | }
510 | }
511 | catch (Exception ex)
512 | {
513 | GlobalVars.Loggi.Error(ex, "Error in StartProgramWithAdminRightsButton_Click: {Message}", ex.Message);
514 | await this.ShowMessageAsync("Error", $"An unexpected error occurred: {ex.Message}");
515 | }
516 | }
517 | #endregion
518 |
519 | #region Imput changed events
520 | private void PasswordTextBox_PasswordChanged(object sender, RoutedEventArgs e)
521 | {
522 | try
523 | {
524 | GlobalVars.SettingsHelper.Password = Core.SecurityHelper.Encrypt(PasswordTextBox.Password);
525 | }
526 | catch (Exception ex)
527 | {
528 | GlobalVars.Loggi.Error(ex, ex.Message);
529 | }
530 | }
531 |
532 | private void DomainComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
533 | {
534 | try
535 | {
536 | GlobalVars.SettingsHelper.Domain = DomainComboBox.SelectedItem.ToString();
537 | }
538 | catch (Exception ex)
539 | {
540 | GlobalVars.Loggi.Error(ex, ex.Message);
541 | }
542 | }
543 |
544 | private void UsernameComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
545 | {
546 | try
547 | {
548 | GlobalVars.SettingsHelper.Username = UsernameComboBox.SelectedItem.ToString();
549 | }
550 | catch (Exception ex)
551 | {
552 | GlobalVars.Loggi.Error(ex, ex.Message);
553 | }
554 | }
555 | #endregion
556 |
557 | private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
558 | {
559 | try
560 | {
561 | // Cancel the update check task
562 | UpdateCheckCts?.Cancel();
563 |
564 | // Log the shutdown
565 | GlobalVars.Loggi.Information("Application is shutting down gracefully");
566 |
567 | // Perform graceful shutdown
568 | Application.Current.Shutdown();
569 | }
570 | catch (Exception ex)
571 | {
572 | GlobalVars.Loggi.Error(ex, "Error during application shutdown");
573 | // Only in case of error, force termination
574 | Environment.Exit(1);
575 | }
576 | }
577 | }
578 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------