Пример #1
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);
            }
        }
Пример #2
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);
 }
Пример #3
0
        public static void Generate(string computerName, SyncList <DprNetworkInfo> result)
        {
            Helpers.AssertNotNull(result, @"result SyncList cannot be null");
            Helpers.AssertString(computerName, @"Computer name cannot be empty");
            var networkInfoList = new List <DprNetworkInfo>( );

            try {
                WmiHelpers.ForEach(computerName, @"SELECT * FROM Win32_NetworkAdapterConfiguration", obj => {
                    var ci = new DprNetworkInfo(computerName);
                    ci.DefaultIpGateway             = WmiHelpers.GetStringArray(obj, @"DefaultIPGateway");
                    ci.Description                  = WmiHelpers.GetString(obj, @"Description");
                    ci.DhcpEnabled                  = WmiHelpers.GetBoolean(obj, @"DHCPEnabled");
                    ci.DhcpLeaseExpires             = WmiHelpers.GetNullableDate(obj, @"DHCPLeaseExpires", true);
                    ci.DhcpLeaseObtained            = WmiHelpers.GetNullableDate(obj, @"DHCPLeaseObtained", true);
                    ci.DhcpServer                   = WmiHelpers.GetString(obj, @"DHCPServer");
                    ci.DnsDomain                    = WmiHelpers.GetString(obj, @"DNSDomain");
                    ci.DnsDomainSuffixSearchOrder   = WmiHelpers.GetStringArray(obj, @"DNSDomainSuffixSearchOrder");
                    ci.DnsEnabledForWinsResolution  = WmiHelpers.GetNullableBoolean(obj, @"DNSEnabledForWINSResolution");
                    ci.DnsHostName                  = WmiHelpers.GetString(obj, @"DNSHostName");
                    ci.DnsServerSearchOrder         = WmiHelpers.GetStringArray(obj, @"DNSServerSearchOrder");
                    ci.DomainDnsRegistrationEnabled = WmiHelpers.GetNullableBoolean(obj, @"DomainDNSRegistrationEnabled");
                    ci.FullDnsRegistrationEnabled   = WmiHelpers.GetNullableBoolean(obj, @"FullDNSRegistrationEnabled");
                    ci.Index                   = WmiHelpers.GetUInt(obj, @"Index");
                    ci.InterfaceIndex          = WmiHelpers.GetUInt(obj, @"InterfaceIndex");
                    ci.IpAddress               = WmiHelpers.GetStringArray(obj, @"IPAddress");
                    ci.IpConnectionMetric      = WmiHelpers.GetNullableUInt(obj, @"IPConnectionMetric");
                    ci.IpEnabled               = WmiHelpers.GetNullableBoolean(obj, @"IPEnabled");
                    ci.MacAddress              = WmiHelpers.GetString(obj, @"MACAddress");
                    ci.SettingId               = WmiHelpers.GetString(obj, @"SettingID");
                    ci.WinsEnableLmHostsLookup = WmiHelpers.GetNullableBoolean(obj, @"WINSEnableLMHostsLookup");
                    ci.WinsHostLookupFile      = WmiHelpers.GetString(obj, @"WINSHostLookupFile");
                    ci.WinsPrimaryServer       = WmiHelpers.GetString(obj, @"WINSPrimaryServer");
                    ci.WinsSecondaryServer     = WmiHelpers.GetString(obj, @"WINSSecondaryServer");
                    ci.WinsScopeId             = WmiHelpers.GetString(obj, @"WINSScopeID");

                    networkInfoList.Add(ci);
                    return(true);
                }, true, false);
            } catch (UnauthorizedAccessException) {
                result.Add(new DprNetworkInfo(computerName, ConnectionStatuses.AuthorizationError));
                return;
            } catch (Exception) {
                result.Add(new DprNetworkInfo(computerName, ConnectionStatuses.Error));
                return;
            }
            result.AddRange(networkInfoList);
            ValidateUniqueness(result);
        }
 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);
     });
 }
Пример #5
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);
        }
Пример #6
0
        private void Query( )
        {
            if (null == QueryDataCb)
            {
                return;
            }
            Clear( );
            OnActionStart( );
            var computerNames = GetComputerNamesFromString(txtComputers.Text);

            _dsThreadCount = computerNames.Count;

            foreach (var currentName in computerNames)
            {
                var computerName = currentName;
                new Thread(() => {
                    try {
                        if (WmiHelpers.IsAlive(computerName))
                        {
                            QueryDataCb(computerName, _ds);
                        }
                        else
                        {
                            var value = new T {
                                ComputerName     = computerName,
                                ConnectionStatus = ConnectionStatuses.ConnectionError
                            };
                            InvokeIfNeeded(() => _ds.Add(value));
                        }
                    } finally {
                        if (0 >= Interlocked.Decrement(ref _dsThreadCount))
                        {
                            OnActionEndInvoke( );
                        }
                    }
                }).Start( );
            }
        }
Пример #7
0
        private static void RunWin32ConfigurationFunction(string computerName, uint interfaceIndex, string functionName)
        {
            Helpers.AssertString(computerName, @"computerName is not specified, it is required");
            Helpers.AssertString(functionName, @"functionName is not specified, it is required");
            WmiHelpers.ForEach(computerName, string.Format(@"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE InterfaceIndex={0}", interfaceIndex), obj => {
                var outParams = obj.InvokeMethod(functionName, null, null);
                Helpers.AssertNotNull(outParams, @"Return value from {0} was null.  This is not allowed", functionName);
                var retVal = (NetworkAdapterConfigurationReturnCodes)uint.Parse(outParams[@"returnValue"].ToString( ));
                switch (retVal)
                {
                case NetworkAdapterConfigurationReturnCodes.Sucessful:
                    return(true);

                case NetworkAdapterConfigurationReturnCodes.SucessfulRebootRequired:
                    NotificationWindow.NotificationWindow.AddErrorMessage(@"Computer '{0}' successfully ran {1} but requires a reboot.", computerName, functionName);
                    return(true);

                default:
                    NotificationWindow.NotificationWindow.AddErrorMessage(@"Error running {0} on '{1}'.  Returned a value of {2}", functionName, computerName, retVal);
                    return(false);
                }
            });
        }