Skip to content
Snippets Groups Projects
Commit fe59972d authored by Niko Ehrenfeuchter's avatar Niko Ehrenfeuchter :keyboard:
Browse files

Move AD related methods to ATXCommon.ActiveDirectory.

parent 0788bb49
No related branches found
No related tags found
No related merge requests found
...@@ -37,6 +37,8 @@ ...@@ -37,6 +37,8 @@
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Configuration" /> <Reference Include="System.Configuration" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.DirectoryServices.AccountManagement" />
<Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
...@@ -44,6 +46,7 @@ ...@@ -44,6 +46,7 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="ActiveDirectory.cs" />
<Compile Include="FsUtils.cs" /> <Compile Include="FsUtils.cs" />
<Compile Include="Serializables\DriveToCheck.cs" /> <Compile Include="Serializables\DriveToCheck.cs" />
<Compile Include="Serializables\ServiceConfig.cs" /> <Compile Include="Serializables\ServiceConfig.cs" />
......
using System;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Management;
using NLog;
namespace ATXCommon
{
public static class ActiveDirectory
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Check if a user is currently logged into Windows.
///
/// WARNING: this DOES NOT ACCOUNT for users logged in via RDP!!
/// </summary>
/// See https://stackoverflow.com/questions/5218778/ for the RDP problem.
public static bool NoUserIsLoggedOn() {
var username = "";
try {
var searcher = new ManagementObjectSearcher("SELECT UserName " +
"FROM Win32_ComputerSystem");
var collection = searcher.Get();
username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
}
catch (Exception ex) {
// TODO / FIXME: combine log and admin-email!
var msg = string.Format("Error in getCurrentUsername(): {0}", ex.Message);
Log.Error(msg);
// TODO: FIXME!
// SendAdminEmail(msg);
}
return username == "";
}
/// <summary>
/// Get the user email address from ActiveDirectory.
/// </summary>
/// <param name="username">The username.</param>
/// <returns>Email address of AD user, an empty string if not found.</returns>
public static string GetEmailAddress(string username) {
try {
using (var pctx = new PrincipalContext(ContextType.Domain)) {
using (var up = UserPrincipal.FindByIdentity(pctx, username)) {
if (up != null && !string.IsNullOrWhiteSpace(up.EmailAddress)) {
return up.EmailAddress;
}
}
}
}
catch (Exception ex) {
Log.Warn("Can't find email address for {0}: {1}", username, ex.Message);
}
return "";
}
/// <summary>
/// Get the full user name (human-friendly) from ActiveDirectory.
/// </summary>
/// <param name="username">The username.</param>
/// <returns>A human-friendly string representation of the user principal.</returns>
public static string GetFullUserName(string username) {
try {
using (var pctx = new PrincipalContext(ContextType.Domain)) {
using (var up = UserPrincipal.FindByIdentity(pctx, username)) {
if (up != null)
return up.GivenName + " " + up.Surname;
}
}
}
catch (Exception ex) {
Log.Warn("Can't find full name for {0}: {1}", username, ex.Message);
}
return "";
}
}
}
...@@ -6,9 +6,6 @@ using System.Linq; ...@@ -6,9 +6,6 @@ using System.Linq;
using System.ServiceProcess; using System.ServiceProcess;
using System.IO; using System.IO;
using System.Timers; using System.Timers;
using System.DirectoryServices.AccountManagement;
using System.Globalization;
using System.Management;
using NLog; using NLog;
using NLog.Config; using NLog.Config;
using NLog.Targets; using NLog.Targets;
...@@ -469,7 +466,7 @@ namespace AutoTx ...@@ -469,7 +466,7 @@ namespace AutoTx
} }
// set state to "Running" if no-one is logged on: // set state to "Running" if no-one is logged on:
if (NoUserIsLoggedOn()) { if (ActiveDirectory.NoUserIsLoggedOn()) {
_status.ServiceSuspended = false; _status.ServiceSuspended = false;
if (!string.IsNullOrEmpty(_status.LimitReason)) { if (!string.IsNullOrEmpty(_status.LimitReason)) {
_status.LimitReason = ""; // reset to force a message on next service suspend _status.LimitReason = ""; // reset to force a message on next service suspend
...@@ -512,72 +509,6 @@ namespace AutoTx ...@@ -512,72 +509,6 @@ namespace AutoTx
#endregion #endregion
#region ActiveDirectory, email address, user name, ...
/// <summary>
/// Check if a user is currently logged into Windows.
///
/// WARNING: this DOES NOT ACCOUNT for users logged in via RDP!!
/// </summary>
/// See https://stackoverflow.com/questions/5218778/ for the RDP problem.
private bool NoUserIsLoggedOn() {
var username = "";
try {
var searcher = new ManagementObjectSearcher("SELECT UserName " +
"FROM Win32_ComputerSystem");
var collection = searcher.Get();
username = (string) collection.Cast<ManagementBaseObject>().First()["UserName"];
}
catch (Exception ex) {
// TODO / FIXME: combine log and admin-email!
var msg = string.Format("Error in getCurrentUsername(): {0}", ex.Message);
Log.Error(msg);
SendAdminEmail(msg);
}
return username == "";
}
/// <summary>
/// Get the user email address from ActiveDirectory.
/// </summary>
/// <param name="username">The username.</param>
/// <returns>Email address of AD user, an empty string if not found.</returns>
public string GetEmailAddress(string username) {
try {
using (var pctx = new PrincipalContext(ContextType.Domain)) {
using (var up = UserPrincipal.FindByIdentity(pctx, username)) {
if (up != null && !String.IsNullOrEmpty(up.EmailAddress)) {
return up.EmailAddress;
}
}
}
}
catch (Exception ex) {
Log.Warn("Can't find email address for {0}: {1}", username, ex.Message);
}
return "";
}
/// <summary>
/// Get the full user name (human-friendly) from ActiveDirectory.
/// </summary>
/// <param name="username">The username.</param>
/// <returns>A human-friendly string representation of the user principal.</returns>
public string GetFullUserName(string username) {
try {
using (var pctx = new PrincipalContext(ContextType.Domain)) {
using (var up = UserPrincipal.FindByIdentity(pctx, username)) {
if (up != null) return up.GivenName + " " + up.Surname;
}
}
}
catch (Exception ex) {
Log.Warn("Can't find full name for {0}: {1}", username, ex.Message);
}
return "";
}
#endregion
#region transfer tasks #region transfer tasks
......
...@@ -4,6 +4,7 @@ using System.IO; ...@@ -4,6 +4,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Net.Mail; using System.Net.Mail;
using System.Text; using System.Text;
using ATXCommon;
namespace AutoTx namespace AutoTx
{ {
...@@ -23,7 +24,7 @@ namespace AutoTx ...@@ -23,7 +24,7 @@ namespace AutoTx
} }
if (!recipient.Contains(@"@")) { if (!recipient.Contains(@"@")) {
Log.Debug("Invalid recipient, trying to resolve via AD: {0}", recipient); Log.Debug("Invalid recipient, trying to resolve via AD: {0}", recipient);
recipient = GetEmailAddress(recipient); recipient = ActiveDirectory.GetEmailAddress(recipient);
} }
if (string.IsNullOrWhiteSpace(recipient)) { if (string.IsNullOrWhiteSpace(recipient)) {
Log.Info("Invalid or empty recipient given, NOT sending email!"); Log.Info("Invalid or empty recipient given, NOT sending email!");
...@@ -149,7 +150,7 @@ namespace AutoTx ...@@ -149,7 +150,7 @@ namespace AutoTx
} }
var substitutions = new List<Tuple<string, string>> { var substitutions = new List<Tuple<string, string>> {
Tuple.Create("FACILITY_USER", GetFullUserName(userDir)), Tuple.Create("FACILITY_USER", ActiveDirectory.GetFullUserName(userDir)),
Tuple.Create("HOST_ALIAS", _config.HostAlias), Tuple.Create("HOST_ALIAS", _config.HostAlias),
Tuple.Create("HOST_NAME", Environment.MachineName), Tuple.Create("HOST_NAME", Environment.MachineName),
Tuple.Create("DESTINATION_ALIAS", _config.DestinationAlias), Tuple.Create("DESTINATION_ALIAS", _config.DestinationAlias),
...@@ -181,7 +182,7 @@ namespace AutoTx ...@@ -181,7 +182,7 @@ namespace AutoTx
var userDir = new DirectoryInfo(_status.CurrentTransferSrc).Name; var userDir = new DirectoryInfo(_status.CurrentTransferSrc).Name;
var substitutions = new List<Tuple<string, string>> { var substitutions = new List<Tuple<string, string>> {
Tuple.Create("FACILITY_USER", GetFullUserName(userDir)), Tuple.Create("FACILITY_USER", ActiveDirectory.GetFullUserName(userDir)),
Tuple.Create("HOST_ALIAS", _config.HostAlias), Tuple.Create("HOST_ALIAS", _config.HostAlias),
Tuple.Create("HOST_NAME", Environment.MachineName), Tuple.Create("HOST_NAME", Environment.MachineName),
Tuple.Create("EMAIL_FROM", _config.EmailFrom) Tuple.Create("EMAIL_FROM", _config.EmailFrom)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment