Ejemplo n.º 1
0
 private static DateTime?GetUsersLogonTimestamp(DprCurrentUsers user)
 {
     if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Domain) || Win32.WellKnownSids.ContainsKey(user.Sid))
     {
         return(null);
     }
     WmiHelpers.ForEachWithScope(user.ComputerName, @"SELECT * FROM Win32_LogonSession", (obj, scope) => {
         try {
             var roq = new RelatedObjectQuery(string.Format(@"associators of {{Win32_LogonSession.LogonId='{0}'}} WHERE AssocClass = Win32_LoggedOnUser", WmiHelpers.GetString(obj, @"LogonId")));
             using (var searcher = new ManagementObjectSearcher(scope, roq)) {
                 foreach (var mobObj in searcher.Get( ))
                 {
                     Helpers.AssertNotNull(mobObj, @"WMI Error, null value returned.");
                     var mob    = (ManagementObject)mobObj;
                     var name   = WmiHelpers.GetString(mob, @"Name");
                     var domain = WmiHelpers.GetString(mob, @"Domain");
                     if (!name.Equals(user.UserName) || !domain.Equals(user.Domain))
                     {
                         continue;
                     }
                     user.LastLogon = WmiHelpers.GetNullableDate(obj, @"StartTime");
                     return(false);                            // Found, stop loop
                 }
             }
         } catch (ManagementException ex) {
             GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"Error finding last logon on {0} for {1}\{2}\n{3}", user.ComputerName, user.Domain, user.UserName, ex.Message);
         }
         return(true);
     }, false, false);
     return(user.LastLogon);
 }
Ejemplo n.º 2
0
        public static void ShutdownComputer(ShutdownComputerParameters parameters)
        {
            try {
                const string query = @"SELECT * FROM Win32_OperatingSystem WHERE Primary=TRUE";

                WmiHelpers.ForEach(parameters.ComputerName, query, obj => {
                    var inParams            = obj.GetMethodParameters(@"Win32ShutdownTracker");
                    inParams[@"Comment"]    = parameters.Comment;
                    inParams[@"Flags"]      = parameters.Flags;
                    inParams[@"ReasonCode"] = 1;                        // Maintenance
                    inParams[@"Timeout"]    = parameters.Timeout;
                    var outParams           = obj.InvokeMethod(@"Win32ShutdownTracker", inParams, null);
                    var result = (null == outParams ? null : outParams[@"ReturnValue"]) as uint?;
                    if (null == result || 0 != result)
                    {
                        var message = string.Format(@"Failed to reboot {0} with error {1}", parameters.ComputerName, result);
                        GlobalLogging.WriteLine(Logging.LogSeverity.Error, message);
                        NotificationWindow.NotificationWindow.AddErrorMessage(message);
                    }
                    return(true);
                }, true);
            } catch (UnauthorizedAccessException) {
                var message = string.Format(@"Failed to reboot {0}, permission denied", parameters.ComputerName);
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, message);
                NotificationWindow.NotificationWindow.AddErrorMessage(message);
            } catch (ManagementException e) {
                var message = string.Format("Failed to reboot {0}, WMI Error\n{1}", parameters.ComputerName, e.Message);
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, message);
                NotificationWindow.NotificationWindow.AddErrorMessage(message);
            } catch (Exception e) {
                var message = string.Format("Failed to reboot {0}, unexpected error\n{1}\n{2}", parameters.ComputerName, e.GetType( ).Name, e.Message);
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, message);
                NotificationWindow.NotificationWindow.AddErrorMessage(message);
            }
        }
Ejemplo n.º 3
0
        public static void Generate(string computerName, SyncList.SyncList <DprCurrentUsers> result)
        {
            Helpers.AssertNotNull(result, @"result SyncList cannot be null");
            Helpers.AssertString(computerName, @"Computer name cannot be empty");

            switch (GetNetworkUsers(computerName, ref result))
            {
            case Win32.Error.Success:
                break;

            case Win32.Error.ErrorMoreData:
                break;

            case Win32.Error.ErrorAccessDenied:
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"DprCurrentUsers - Generate - Access Denied for {0}", computerName);
                result.Add(new DprCurrentUsers(computerName, ConnectionStatuses.AccessDenied));
                //return;
                break;

            default:
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"DprCurrentUsers - Generate - Unknown Error for {0}", computerName);
                result.Add(new DprCurrentUsers(computerName, ConnectionStatuses.Error));
                //return;
                break;
            }
            GetLocallyLoggedOnUsers(computerName, result);
            ValidateUniqueness(result);
        }
Ejemplo n.º 4
0
//      public static void Assert( bool condition, string message = "" ) {
//          if( condition ) {
//              return;
//          }
//          var trace = new StackTrace( 1 );
//          GlobalLogging.WriteLine( Logging.LogSeverity.Fatal, @"Assertion Failure - {0} - {1}", message, trace );
//          MessageBox.Show( String.Format( "{0}\n{1}", message, trace ), @"Assertion Fail", MessageBoxButtons.OK, MessageBoxIcon.Error );
//          Application.Exit( );
//      }
//
        private static void AssertCondition(bool condition, string messageFormat, params object[] messageValues)
        {
            if (condition)
            {
                return;
            }
            var trace   = new StackTrace(2);
            var message = string.Format(messageFormat, messageValues);

            GlobalLogging.WriteLine(Logging.LogSeverity.Fatal, @"Assertion Failure - {0} - {1}", message, trace);
            throw new AssertionException(message);
        }
Ejemplo n.º 5
0
        public static byte[] StringToBinarySid(string sid)
        {
            SecurityIdentifier si;

            try {
                si = new SecurityIdentifier(sid);
            } catch (ArgumentException ex) {
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, "Exception while looking up SID\n{0}", ex.Message);
                return(null);
            }
            var binSid = new byte[si.BinaryLength];

            si.GetBinaryForm(binSid, 0);
            return(binSid);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Checks if the hostname is resolvable and pingable
 /// </summary>
 /// <param name="computerName">The test host system</param>
 /// <param name="timeoutMs">How long to wait for a ping replay in ms</param>
 /// <returns></returns>
 public static bool IsAlive(string computerName, int timeoutMs = 3000)
 {
     try {
         using (var pingSender = new Ping( )) {
             var reply = pingSender.Send(computerName, timeoutMs);
             if (null != reply && IPStatus.Success == reply.Status)
             {
                 return(true);
             }
             Debug.Assert(reply != null, "Ping reply was null, this shouldn't happen");
             GlobalLogging.WriteLine(Logging.LogSeverity.Info, @"Ping Status for '{0}' is {1}", computerName, reply.Status);
             return(false);
         }
     } catch (Exception) {
         return(false);
     }
 }
Ejemplo n.º 7
0
        private static void GetUserAccountFromSid(ref DprCurrentUsers user)
        {
            var binSid = Win32.StringToBinarySid(user.Sid);

            if (null == binSid)
            {
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"DgvHelpers - GetNetworkUsers - Error Resolving SID");
                user.ConnectionStatus = ConnectionStatuses.ErrorResolvingSid;
                return;
            }
            var name    = new StringBuilder( );
            var cchName = (uint)name.Capacity;
            var referencedDomainName    = new StringBuilder( );
            var cchReferencedDomainName = (uint)referencedDomainName.Capacity;

            Win32.SidNameUse sidUse;

            var err = Win32.Error.Success;

            if (!Win32.LookupAccountSid(null, binSid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
            {
                err = (Win32.Error)Marshal.GetLastWin32Error( );
                if (Win32.Error.ErrorInsufficientBuffer == err)
                {
                    name.EnsureCapacity((int)cchName);
                    referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
                    err = Win32.Error.Success;
                    if (!Win32.LookupAccountSid(null, binSid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
                    {
                        err = (Win32.Error)Marshal.GetLastWin32Error( );
                    }
                }
            }
            if (Win32.Error.Success == err)
            {
                user.UserName = name.ToString( );
                user.Domain   = referencedDomainName.ToString( );
            }
            else
            {
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"DgvHelpers - GetNetworkUsers - Error Resolving SID - Error ", err);
                user.ConnectionStatus = ConnectionStatuses.ErrorResolvingSid;
            }
        }
 public static void UninstallGuidOnComputerName(string computerName, string guid)
 {
     Helpers.AssertString(computerName, @"computerName cannot be null or empty");
     Helpers.AssertString(guid, @"Guid cannot be null or empty");
     WmiHelpers.ForEach(computerName, string.Format(@"SELECT * FROM Win32_Product WHERE IdentifyingNumber='{0}'", guid), obj => {
         GlobalLogging.WriteLine(Logging.LogSeverity.Info, @"Uninstalling '{0}' from {1}", obj.Properties["Name"].Value, computerName);
         var outParams = obj.InvokeMethod(@"Uninstall", null, null);
         Debug.Assert(outParams != null, @"Return value from uninstall was null.  This is not allowed");
         var retVal = int.Parse(outParams[@"returnValue"].ToString( ));
         if (0 != retVal)
         {
             var message = string.Format(@"Error uninstalling '{0}' from {1}. Returned a value of {2}", obj.Properties["Name"].Value, computerName, retVal);
             GlobalLogging.WriteLine(Logging.LogSeverity.Warning, message);
             NotificationWindow.NotificationWindow.AddErrorMessage(message);
             return(false);                      // Stop all on error.  This might be wrong
         }
         return(true);
     });
 }
Ejemplo n.º 9
0
        public static void Generate(string computerName, SyncList.SyncList <DprComputerInfo> result)
        {
            Helpers.AssertNotNull(result, @"result SyncList cannot be null");
            Helpers.AssertString(computerName, @"Computer name cannot be empty");
            var ci = new DprComputerInfo(computerName)
            {
                LocalSystemDateTime = DateTime.Now
            };

            try {
                WmiHelpers.ForEach(computerName, @"SELECT * FROM Win32_OperatingSystem WHERE Primary=TRUE", obj => {
                    ci.LastBootTime = WmiHelpers.GetNullableDate(obj, @"LastBootUpTime");
                    ci.SystemTime   = WmiHelpers.GetNullableDate(obj, @"LocalDateTime");
                    ci.Version      = WmiHelpers.GetString(obj, @"Caption");
                    ci.Architecture = WmiHelpers.GetString(obj, @"OSArchitecture");
                    ci.InstallDate  = WmiHelpers.GetNullableDate(obj, @"InstallDate");
                    return(true);
                });

                WmiHelpers.ForEach(computerName, @"SELECT * FROM Win32_BIOS", obj => {
                    ci.Manufacturer  = WmiHelpers.GetString(obj, @"Manufacturer");
                    ci.HwReleaseDate = WmiHelpers.GetNullableDate(obj, @"ReleaseDate");
                    ci.SerialNumber  = WmiHelpers.GetString(obj, @"SerialNumber");
                    ci.BiosVersion   = WmiHelpers.GetString(obj, @"SMBIOSBIOSVersion");
                    return(true);
                });

                WmiHelpers.ForEach(computerName, @"SELECT * FROM Win32_ComputerSystem", obj => {
                    ci.Model = WmiHelpers.GetString(obj, @"Model");
                    ci.TotalPhysicalMemory = WmiHelpers.GetUInt(obj, @"TotalPhysicalMemory");
                    return(true);
                });
            } catch (UnauthorizedAccessException uae) {
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"Exception - {0} - {1}", uae.TargetSite, uae.Message);
                ci.ConnectionStatus = ConnectionStatuses.AuthorizationError;
            } catch (Exception ex) {
                GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"Exception - {0} - {1}", ex.TargetSite, ex.Message);
                ci.ConnectionStatus = ConnectionStatuses.Error;
            }
            result.Add(ci);
            ValidateUniqueness(result);
        }
Ejemplo n.º 10
0
 public static void AddColumnBasedOnDataType(DataGridView dgv, Type columnType, string columnName)
 {
     if (Helpers.TypeChecks.IsString(columnType) || Helpers.TypeChecks.IsNumber(columnType) || Helpers.TypeChecks.IsEnum(columnType))
     {
         AddColumn(dgv, columnName, Helpers.CamelToSpace(columnName));
     }
     else if (Helpers.TypeChecks.IsDateTime(columnType))
     {
         AddDateColumn(dgv, columnName, Helpers.CamelToSpace(columnName), false, true, MagicValues.TimeDateStringFormat);
     }
     else if (Helpers.TypeChecks.IsBool(columnType))
     {
         AddCheckedColumn(dgv, columnName, Helpers.CamelToSpace(columnName));
     }
     else
     {
         const string message = @"Have not accounted for this type in DGVHelpers AddColumnBasedOnType";
         GlobalLogging.WriteLine(Logging.LogSeverity.Fatal, @"AddColumnBasedOnDataType - {0}", message);
         throw new UnsupportedTypeException(columnType, message);
     }
 }
Ejemplo n.º 11
0
        private static void GetLocallyLoggedOnUsers(string computerName, SyncList.SyncList <DprCurrentUsers> result)
        {
            var usersList = new List <DprCurrentUsers>( );

            using (var regHku = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, string.Empty)) {
                foreach (var currentSid in regHku.GetSubKeyNames( ).Where(IsSid))
                {
                    var cu = new DprCurrentUsers(computerName)
                    {
                        Sid = currentSid
                    };
                    try {
                        if (Win32.WellKnownSids.ContainsKey(currentSid))
                        {
                            cu.Domain   = computerName;                                 // Local account
                            cu.UserName = Win32.WellKnownSids[currentSid];
                        }
                        else
                        {
                            GetUserAccountFromSid(ref cu);
                        }
                        cu.ProfileFolder = RegistryHelpers.GetString(computerName, RegistryHive.LocalMachine, string.Format(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{0}", currentSid), @"ProfileImagePath");
                        cu.LastLogon     = GetUsersLogonTimestamp(cu);
                    } catch (Exception ex) {
                        GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"Exception - {0} - {1}", ex.TargetSite, ex.Message);
                        cu = new DprCurrentUsers(computerName, ConnectionStatuses.Error)
                        {
                            Sid = currentSid
                        };
                    }
                    cu.LogonType = LogonTypes.Local;
                    usersList.Add(cu);
                }
            }
            result.AddRange(usersList);
        }
Ejemplo n.º 12
0
        private static Win32.Error GetNetworkUsers(string computerName, ref SyncList.SyncList <DprCurrentUsers> result)
        {
            Win32.Error res;
            var         er        = 0;
            var         tr        = 0;
            var         resume    = 0;
            var         buffer    = IntPtr.Zero;
            var         usersList = new List <DprCurrentUsers>( );

            do
            {
                try {
                    res = (Win32.Error)Win32.NetSessionEnum(computerName, null, null, 502, out buffer, -1, ref er, ref tr, ref resume);
                    if (res == Win32.Error.ErrorMoreData || res == Win32.Error.Success)
                    {
                        var bufferPtrInt = buffer.ToInt32( );
                        for (var i = 0; i < er; i++)
                        {
                            var sessionInfo = (Win32.SessionInfo502)Marshal.PtrToStructure(new IntPtr(bufferPtrInt), typeof(Win32.SessionInfo502));
                            var cu          = new DprCurrentUsers(computerName)
                            {
                                UserName = sessionInfo.userName, LastLogon = DateTime.Now.AddSeconds(-sessionInfo.logonDuration), LogonType = LogonTypes.Share
                            };
                            usersList.Add(cu);
                            bufferPtrInt += Marshal.SizeOf(typeof(Win32.SessionInfo502));
                        }
                    }
                    else
                    {
                        switch (res)
                        {
                        case Win32.Error.ErrorAccessDenied:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Access Denied: {0}", computerName);
                            break;

                        case Win32.Error.ErrorNotEnoughMemory:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Not Enough Memory: {0}", computerName);
                            break;

                        case Win32.Error.ErrorBadNetpath:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Bad Network Path: {0}", computerName);
                            break;

                        case Win32.Error.ErrorNetworkBusy:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Network Busy: {0}", computerName);
                            break;

                        case Win32.Error.ErrorInvalidParameter:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Invalid Parameter: {0}", computerName);
                            break;

                        case Win32.Error.ErrorInsufficientBuffer:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Insufficient Buff: {0}", computerName);
                            break;

                        case Win32.Error.ErrorInvalidLevel:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Invalid Level: {0}", computerName);
                            break;

                        case Win32.Error.ErrorExtendedError:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Exended Error: {0}", computerName);
                            break;

                        case Win32.Error.ErrorNoNetwork:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: No Network: {0}", computerName);
                            break;

                        case Win32.Error.ErrorInvalidHandleState:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Invalid Handle State: {0}", computerName);
                            break;

                        case Win32.Error.NerrBase:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: NERR_BASE: {0}", computerName);
                            break;

                        case Win32.Error.NerrUnknownDevDir:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Unknown Device Directory: {0}", computerName);
                            break;

                        case Win32.Error.NerrDuplicateShare:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Duplicate Share: {0}", computerName);
                            break;

                        case Win32.Error.NerrBufTooSmall:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: Buffer too small: {0}", computerName);
                            break;

                        case Win32.Error.ErrorNoBrowserServersFound:
                            GlobalLogging.WriteLine(Logging.LogSeverity.Error, @"GetNetworkUsers: No Browser Servers Found: {0}", computerName);
                            break;
                        }
                        return(res);
                    }
                } finally {
                    if (IntPtr.Zero != buffer)
                    {
                        Win32.NetApiBufferFree(buffer);
                    }
                }
            } while(res == Win32.Error.ErrorMoreData);
            result.AddRange(usersList);
            return(Win32.Error.Success);
        }