public override bool Verify()
        {
            bool flag = WmiWrapper.IsServiceRunning(this.computerName, "MSExchangeIS");

            TaskLogger.Trace("InformationStoreServiceRunningCondition.Verify() returns {0}: <Server '{1}'>", new object[]
            {
                flag,
                this.computerName
            });
            return(flag);
        }
        public override bool Verify()
        {
            bool flag = WmiWrapper.IsPathOnFixedOrNetworkDrive(base.ComputerName, base.PathName);

            TaskLogger.Trace("PathOnFixedOrNetworkDriveCondition.Verify() returns {0}: <Server '{1}', PathName '{2}'>", new object[]
            {
                flag,
                base.ComputerName,
                base.PathName
            });
            return(flag);
        }
        public override bool Verify()
        {
            bool flag = !WmiWrapper.IsFileExisting(base.ComputerName, base.PathName);

            TaskLogger.Trace("FileNotExistCondition.Verify() returns {0}: <Server '{1}', FileName '{2}'>", new object[]
            {
                flag,
                base.ComputerName,
                base.PathName
            });
            return(flag);
        }
Пример #4
0
 public void Delete(bool forceDelete)
 {
     if (this.Exists())
     {
         if (!this.m_isJustCreated)
         {
             if (!forceDelete)
             {
                 return;
             }
         }
         try
         {
             TaskLogger.Trace("Attempting to delete witness share \\\\{0}\\{1}. Just created: {2}, forced: {3}", new object[]
             {
                 this.WitnessServer,
                 this.ShareName,
                 this.m_isJustCreated,
                 forceDelete
             });
             NetShare.DeleteShare(this.WitnessServerFqdn, this.ShareName);
             WmiWrapper.RemoveDirectory(this.WitnessServerFqdn, this.WitnessDirectory.ToString());
             this.m_exists = new bool?(false);
             TaskLogger.Trace("Attempt to delete witness share \\\\{0}\\{1} succeeded.", new object[]
             {
                 this.WitnessServer,
                 this.ShareName
             });
         }
         catch (WmiException ex)
         {
             throw new DagFswUnableToRemoveWitnessDirectoryException(this.WitnessServerFqdn, this.WitnessDirectory.ToString(), ex);
         }
         catch (Win32Exception ex2)
         {
             if ((long)ex2.NativeErrorCode == 2310L)
             {
                 this.m_exists = new bool?(false);
             }
             else
             {
                 if (ex2.NativeErrorCode == 5)
                 {
                     throw new DagFswInsufficientPermissionsToDeleteFswException(this.WitnessServerFqdn, this.FileShareWitnessShare.ToString(), ex2);
                 }
                 throw new DagFswServerNotAccessibleToDeleteFswException(this.WitnessServerFqdn, this.FileShareWitnessShare.ToString(), ex2);
             }
         }
     }
 }
        private void ForceKillAssistantService(Process process)
        {
            ManagementObject processObject = WmiWrapper.GetProcessObject(this.ExchangeServer.Fqdn, "MsExchangeMailboxAssistants.exe");

            if (processObject != null)
            {
                uint num = (uint)processObject.InvokeMethod("Terminate", new object[]
                {
                    0
                });
                if (num != 0U)
                {
                    throw new Win32Exception((int)num, Strings.MailboxAssistantsServiceCouldNotBeKilled(process.MachineName).ToString());
                }
            }
        }
        private void SaveLocalPath()
        {
            DirectoryEntry directoryEntry;

            try
            {
                directoryEntry = IisUtility.FindWebObject(this.Parent, this.Name, "IIsWebVirtualDir");
            }
            catch (WebObjectNotFoundException)
            {
                return;
            }
            this.serverName = IisUtility.GetHostName(this.parent);
            if (WmiWrapper.IsDirectoryExisting(this.serverName, (string)directoryEntry.Properties["Path"].Value))
            {
                this.localPath = (string)directoryEntry.Properties["Path"].Value;
            }
        }
        internal void SuspendDatabaseCopyIfNecessary(ReplayConfiguration config)
        {
            string text = string.Empty;

            text = config.TargetMachine;
            if (!this.m_fConfigOnly && !WmiWrapper.IsFileExisting(text, config.DestinationEdbPath))
            {
                string fileName = string.Empty;
                fileName = Path.Combine(config.DestinationLogPath, EseHelper.MakeLogfileName(config.LogFilePrefix, "." + config.LogExtension, 1L));
                if (!WmiWrapper.IsFileExisting(SharedHelper.GetFqdnNameFromNode(config.SourceMachine), fileName))
                {
                    try
                    {
                        this.WriteWarning(Strings.EnableDBCSuspendReplayNoDbComment(config.Name));
                        ReplayRpcClientWrapper.RequestSuspend(text, config.IdentityGuid, Strings.EnableDBCSuspendReplayNoDbComment(config.Name));
                        ReplayEventLogConstants.Tuple_DbSeedingRequired.LogEvent(null, new object[]
                        {
                            config.Name,
                            text
                        });
                    }
                    catch (TaskServerTransientException ex)
                    {
                        ExTraceGlobals.CmdletsTracer.TraceDebug <TaskServerTransientException>((long)this.GetHashCode(), "SeedDatabase: Caught exception in RPC: {0}", ex);
                        base.WriteError(new InvalidOperationException(Strings.SgcFailedToSuspendRpc(config.Name, ex.Message)), ErrorCategory.InvalidOperation, this.Identity);
                    }
                    catch (TaskServerException ex2)
                    {
                        ExTraceGlobals.CmdletsTracer.TraceDebug <TaskServerException>((long)this.GetHashCode(), "SeedDatabase: Caught exception in RPC: {0}", ex2);
                        if (!(ex2 is ReplayServiceSuspendWantedSetException))
                        {
                            if (ex2 is ReplayServiceSuspendRpcPartialSuccessCatalogFailedException)
                            {
                                base.WriteWarning(ex2.Message);
                            }
                            else
                            {
                                base.WriteError(new InvalidOperationException(Strings.SgcFailedToSuspendRpc(config.Name, ex2.Message)), ErrorCategory.InvalidOperation, this.Identity);
                            }
                        }
                    }
                }
            }
        }
        public static bool CheckSeedingPath(string machineFqdn, string logFolderPath, string edbFilePath, string logPrefix)
        {
            LocalLongFullPath.Parse(logFolderPath);
            LocalLongFullPath.Parse(edbFilePath);
            string directoryName = Path.GetDirectoryName(edbFilePath);

            string[] array = new string[]
            {
                logFolderPath,
                directoryName
            };
            string[] array2 = new string[]
            {
                "LogFolderPath",
                "EdbFolderPath"
            };
            for (int i = 0; i < array.Length; i++)
            {
                if (WmiWrapper.IsFileExisting(machineFqdn, array[i]))
                {
                    throw new SeedingPathErrorException(Strings.SeedingErrorDirectoryIsFile(array2[i], array[i]));
                }
            }
            string text = Path.Combine(logFolderPath, logPrefix + ".log");

            if (WmiWrapper.IsDirectoryExisting(machineFqdn, text))
            {
                throw new SeedingPathErrorException(Strings.SeedingErrorFileIsDirectory("CopyLogFile", text));
            }
            if (WmiWrapper.IsDirectoryExisting(machineFqdn, edbFilePath))
            {
                throw new SeedingPathErrorException(Strings.SeedingErrorFileIsDirectory("CopyEdbFilePath", edbFilePath));
            }
            if (WmiWrapper.IsFileExisting(machineFqdn, edbFilePath))
            {
                throw new SeedingPathWarningException(Strings.SeedingEdbFileExists(edbFilePath));
            }
            if (WmiWrapper.IsFileExisting(machineFqdn, text))
            {
                throw new SeedingPathWarningException(Strings.SeedingLogFileExists(text));
            }
            return(true);
        }
Пример #9
0
        private bool TryDeleteFile(string targetFilePath)
        {
            bool result;

            try
            {
                base.WriteVerbose(Strings.VerboseDeleteFile(base.OwnerServerName, targetFilePath));
                result = WmiWrapper.DeleteFileIfExists(this.OwnerServer.Fqdn, targetFilePath);
            }
            catch (ManagementException ex)
            {
                base.WriteVerbose(Strings.VerboseEatUpException(ex.Message));
                TaskLogger.Trace("MoveDatabasePath.TryDeleteFile raises exception: {0}", new object[]
                {
                    ex.ToString()
                });
                result = false;
            }
            return(result);
        }
Пример #10
0
        public static MRSHealthCheckOutcome VerifyServiceIsUp(string serverName, string fqdn, TestMRSHealth testMRSCmdlet = null)
        {
            MRSHealthCheckOutcome result;

            try
            {
                using (ManagementObject serviceObject = WmiWrapper.GetServiceObject(fqdn, "MSExchangeMailboxReplication"))
                {
                    if (serviceObject == null)
                    {
                        if (testMRSCmdlet != null)
                        {
                            testMRSCmdlet.MonitoringData.Events.Add(new MonitoringEvent("MSExchange Monitoring MRSHealth", 1001, EventTypeEnumeration.Error, Strings.MailboxReplicationServiceNotInstalled));
                        }
                        result = new MRSHealthCheckOutcome(serverName, MRSHealthCheckId.ServiceCheck, false, Strings.MailboxReplicationServiceNotInstalled);
                    }
                    else if (!StringComparer.InvariantCultureIgnoreCase.Equals(serviceObject["State"] as string, "Running"))
                    {
                        if (testMRSCmdlet != null)
                        {
                            testMRSCmdlet.MonitoringData.Events.Add(new MonitoringEvent("MSExchange Monitoring MRSHealth", 1001, EventTypeEnumeration.Error, Strings.MailboxReplicationServiceNotRunning));
                        }
                        result = new MRSHealthCheckOutcome(serverName, MRSHealthCheckId.ServiceCheck, false, Strings.MailboxReplicationServiceNotRunning);
                    }
                    else
                    {
                        result = new MRSHealthCheckOutcome(serverName, MRSHealthCheckId.ServiceCheck, true, Strings.MailboxReplicationServiceIsRunning);
                    }
                }
            }
            catch (WmiException ex)
            {
                ServiceHealthWmiFailureException ex2 = new ServiceHealthWmiFailureException(ex.Message, ex);
                if (testMRSCmdlet != null)
                {
                    testMRSCmdlet.WriteErrorAndMonitoringEvent(ex2, ErrorCategory.ReadError, 1001);
                }
                result = new MRSHealthCheckOutcome(serverName, MRSHealthCheckId.ServiceCheck, false, CommonUtils.FullExceptionMessage(ex2, true));
            }
            return(result);
        }
        public override bool Verify()
        {
            string dirName = null;

            try
            {
                dirName = LocalLongFullPath.ParseFromPathNameAndFileName(base.PathName, this.logPrefix + ".log").PathName;
            }
            catch (ArgumentException ex)
            {
                TaskLogger.Trace("LogLocationAvailableCondition.Verify() caught exception '{0}': <Server '{1}', PathName '{2}'>", new object[]
                {
                    ex.Message,
                    base.ComputerName,
                    base.PathName
                });
                return(false);
            }
            bool flag = true;

            if (WmiWrapper.IsDirectoryExisting(base.ComputerName, dirName))
            {
                flag = false;
            }
            else if (WmiWrapper.IsFileExistingInPath(base.ComputerName, base.PathName, new WmiWrapper.FileFilter(this.LogFileFilter)))
            {
                flag = false;
            }
            else if (WmiWrapper.IsFileExisting(base.ComputerName, base.PathName))
            {
                flag = false;
            }
            TaskLogger.Trace("LogLocationAvailableCondition.Verify() returns {0}: <Server '{1}', PathName '{2}'>", new object[]
            {
                flag,
                base.ComputerName,
                base.PathName
            });
            return(flag);
        }
Пример #12
0
        public override bool Verify()
        {
            string text = null;

            try
            {
                text = LocalLongFullPath.ParseFromPathNameAndFileName(base.PathName, "tmp.edb").PathName;
            }
            catch (ArgumentException ex)
            {
                TaskLogger.Trace("SystemPathAvailableCondition.Verify() caught exception '{0}': <Server '{1}', PathName '{2}'>", new object[]
                {
                    ex.Message,
                    base.ComputerName,
                    base.PathName
                });
                return(false);
            }
            bool flag = true;

            if (WmiWrapper.IsDirectoryExisting(base.ComputerName, text))
            {
                flag = false;
            }
            else if (WmiWrapper.IsFileExisting(base.ComputerName, text))
            {
                flag = false;
            }
            else if (WmiWrapper.IsFileExisting(base.ComputerName, base.PathName))
            {
                flag = false;
            }
            TaskLogger.Trace("SystemPathAvailableCondition.Verify() returns {0}: <Server '{1}', PathName '{2}'>", new object[]
            {
                flag,
                base.ComputerName,
                base.PathName
            });
            return(flag);
        }
Пример #13
0
        public static IEnumerable <LastLoggedOnUser> Get_WMIRegLastLoggedOn(Args_Get_WMIRegLastLoggedOn args = null)
        {
            if (args == null)
            {
                args = new Args_Get_WMIRegLastLoggedOn();
            }

            var LastLoggedOnUsers = new List <LastLoggedOnUser>();

            foreach (var Computer in args.ComputerName)
            {
                // HKEY_LOCAL_MACHINE
                var HKLM = 2147483650;

                // try to open up the remote registry key to grab the last logged on user
                try
                {
                    var Reg = WmiWrapper.GetClass($@"\\{Computer}\ROOT\DEFAULT", "StdRegProv", args.Credential);
                    var Key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI";

                    var Value     = "LastLoggedOnUser";
                    var outParams = WmiWrapper.CallMethod(Reg, "GetStringValue", new Dictionary <string, object> {
                        { "hDefKey", HKLM }, { "sSubKeyName", Key }, { "sValueName", Value }
                    }) as System.Management.ManagementBaseObject;
                    var LastUser = outParams["sValue"] as string;

                    var LastLoggedOn = new LastLoggedOnUser
                    {
                        ComputerName = Computer,
                        LastLoggedOn = LastUser
                    };
                    LastLoggedOnUsers.Add(LastLoggedOn);
                }
                catch
                {
                    Logger.Write_Warning("[Get-WMIRegLastLoggedOn] Error opening remote registry on $Computer. Remote registry likely not enabled.");
                }
            }
            return(LastLoggedOnUsers);
        }
Пример #14
0
        private bool TryCopyPath(string originalPath, string newPath, WmiWrapper.FileFilter filter)
        {
            bool result = true;

            try
            {
                if (SystemConfigurationTasksHelper.TryCreateDirectory(this.ownerServer.Fqdn, newPath, Database_Directory.GetDomainWidePermissions(), new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), new Task.TaskWarningLoggingDelegate(this.WriteWarning)))
                {
                    base.WriteVerbose(Strings.VerboseCheckDirectoryExistenceCondition(this.OwnerServer.Fqdn, originalPath));
                    if (WmiWrapper.IsDirectoryExisting(this.OwnerServer.Fqdn, originalPath))
                    {
                        base.WriteVerbose(Strings.VerboseCopyDirectory(this.OwnerServer.Fqdn, originalPath, newPath));
                        if (!WmiWrapper.CopyFilesInDirectory(this.OwnerServer.Fqdn, originalPath, newPath, filter))
                        {
                            result = false;
                        }
                    }
                    else
                    {
                        TaskLogger.Trace("Original directory does not exist, nothing to copy.", new object[0]);
                    }
                }
                else
                {
                    result = false;
                }
            }
            catch (ManagementException ex)
            {
                base.WriteVerbose(Strings.VerboseEatUpException(ex.Message));
                TaskLogger.Trace("Error occurs when copying path: {0}", new object[]
                {
                    ex.Message
                });
                result = false;
            }
            return(result);
        }
Пример #15
0
        public static IEnumerable <UserProcess> Get_WMIProcess(Args_Get_WMIProcess args = null)
        {
            if (args == null)
            {
                args = new Args_Get_WMIProcess();
            }

            var UserProcesses = new List <UserProcess>();

            foreach (var Computer in args.ComputerName)
            {
                try
                {
                    var cls   = WmiWrapper.GetClass($@"\\{Computer}\ROOT\CIMV2", "Win32_process", args.Credential);
                    var procs = WmiWrapper.GetInstances(cls);
                    foreach (var proc in procs)
                    {
                        var owner       = WmiWrapper.CallMethod(proc, "GetOwner");
                        var UserProcess = new UserProcess
                        {
                            ComputerName = Computer,
                            ProcessName  = proc.Properties["Caption"].Value.ToString(),
                            ProcessID    = proc.Properties["ProcessId"].Value.ToString(),
                            Domain       = $@"{owner["Domain"]}",
                            User         = $@"{owner["User"]}",
                        };
                        UserProcesses.Add(UserProcess);
                    }
                }
                catch (Exception e)
                {
                    Logger.Write_Verbose($@"[Get-WMIProcess] Error enumerating remote processes on '{Computer}', access likely denied: {e}");
                }
            }
            return(UserProcesses);
        }
Пример #16
0
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter(new object[]
            {
                this.DataObject
            });
            bool       flag   = false;
            bool       flag2  = false;
            bool       flag3  = true;
            bool       flag4  = false;
            bool       flag5  = false;
            Server     server = this.OwnerServer;
            ADObjectId id     = new ADObjectId(this.OwnerServer.Guid);

            if (server == null)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorDBOwningServerNotFound(this.DataObject.Identity.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
            }
            try
            {
                if ((!this.IsEdbFilePathChanged && !this.isLogFolderPathChanged) || (base.ConfigurationOnly && !this.shouldContinueToDoConfigurationOnly))
                {
                    TaskLogger.LogExit();
                }
                else
                {
                    if (this.needReportProgress)
                    {
                        base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressCheckingReplayState, 10);
                    }
                    base.WriteVerbose(Strings.VerboseConnectionAdminRpcInterface(this.OwnerServer.Fqdn));
                    MdbStatus mdbStatus = AmStoreHelper.GetMdbStatus(this.OwnerServer.Fqdn, this.DataObject.Guid);
                    if (mdbStatus == null)
                    {
                        base.WriteError(new InvalidOperationException(Strings.ErrorFailedToGetDatabaseStatus(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.Identity);
                    }
                    if ((mdbStatus.Status & MdbStatusFlags.Backup) != MdbStatusFlags.Offline)
                    {
                        base.WriteError(new InvalidOperationException(Strings.ErrorBackupInProgress(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.Identity);
                    }
                    else if ((mdbStatus.Status & MdbStatusFlags.Online) != MdbStatusFlags.Offline)
                    {
                        if (!this.Force && !base.ShouldContinue(base.ConfigurationOnly ? Strings.WarningDismountDatabaseToDoConfigurationOnly(this.Identity.ToString()) : Strings.WarningDismountDatabaseToContinue(this.Identity.ToString())))
                        {
                            TaskLogger.LogExit();
                            return;
                        }
                        if (this.needReportProgress)
                        {
                            base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressDismountingDatabase(this.Identity.ToString()), 20);
                        }
                        base.WriteVerbose(TaskVerboseStringHelper.GetReadObjectVerboseString(id, base.DataSession, typeof(Server)));
                        try
                        {
                            base.WriteVerbose(Strings.VerboseUnmountDatabase(this.DataObject.Identity.ToString()));
                            AmRpcClientHelper.DismountDatabase(ADObjectWrapperFactory.CreateWrapper(this.DataObject), 0);
                        }
                        catch (AmServerException ex)
                        {
                            Exception ex2;
                            if (ex.TryGetInnerExceptionOfType(out ex2))
                            {
                                TaskLogger.Trace("MoveDatabasePath.InternalProcessRecord raises exception while unmounting database: {0}", new object[]
                                {
                                    ex2.Message
                                });
                            }
                            else if (ex.TryGetInnerExceptionOfType(out ex2))
                            {
                                TaskLogger.Trace("MoveDatabasePath.InternalProcessRecord raises exception while unmounting database: {0}", new object[]
                                {
                                    ex2.Message
                                });
                            }
                            else if (ex is AmDatabaseNeverMountedException)
                            {
                                TaskLogger.Trace("MoveDatabasePath.InternalProcessRecord raises exception while unmounting database: {0}", new object[]
                                {
                                    ex.Message
                                });
                            }
                            else
                            {
                                TaskLogger.Trace("MoveDatabasePath.InternalProcessRecord raises exception while unmounting database: {0}", new object[]
                                {
                                    ex.Message
                                });
                                base.WriteError(ex, ErrorCategory.InvalidOperation, this.DataObject.Identity);
                            }
                        }
                        catch (AmServerTransientException ex3)
                        {
                            TaskLogger.Trace("MoveDatabasePath.InternalProcessRecord raises exception while dismounting database: {0}", new object[]
                            {
                                ex3.Message
                            });
                            base.WriteError(ex3, ErrorCategory.InvalidOperation, this.DataObject.Identity);
                        }
                        flag = true;
                    }
                    if (!base.ConfigurationOnly)
                    {
                        if (this.IsDatabaseFilesCreated && this.IsEdbFilePathChanged)
                        {
                            if (this.needReportProgress)
                            {
                                base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressCopyingEdbFile, 25);
                            }
                            if (!this.TryCopyFile(this.OriginalEdbFilePath.PathName, this.TargetEdbFilePath.PathName))
                            {
                                base.WriteError(new InvalidOperationException(Strings.ErrorFailedToMoveEdbFile(this.OriginalEdbFilePath.PathName, this.TargetEdbFilePath.PathName)), ErrorCategory.InvalidOperation, this.Identity);
                            }
                            flag2 = true;
                        }
                        if (this.isLogFolderPathChanged)
                        {
                            if (this.needReportProgress)
                            {
                                base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressCopyingLogFiles, 45);
                            }
                            base.WriteVerbose(Strings.VerboseCopyDatabaseLogFiles(base.OwnerServerName, this.OldLogFolderPath.PathName, this.LogFolderPath.PathName));
                            if (!this.TryCopyPath(this.OldLogFolderPath.PathName, this.LogFolderPath.PathName, new WmiWrapper.FileFilter(this.LogFileFilter)))
                            {
                                base.WriteError(new InvalidOperationException(Strings.ErrorFailedToMoveDatabaseLogFiles(this.OldLogFolderPath.PathName, this.LogFolderPath.PathName)), ErrorCategory.InvalidOperation, this.DataObject.Identity);
                            }
                            flag4 = true;
                        }
                    }
                    if (this.needReportProgress)
                    {
                        base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressSavingADObject, 69);
                    }
                    base.InternalProcessRecord();
                    flag3 = false;
                    if (flag2)
                    {
                        if (this.needReportProgress)
                        {
                            base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressDeletingEdbFile, 72);
                        }
                        if (!this.TryDeleteFile(this.OriginalEdbFilePath.PathName))
                        {
                            this.WriteWarning(Strings.FailedToDeleteOldEdbFile(this.OriginalEdbFilePath.PathName));
                            TaskLogger.Trace("MoveDatabasePath: delete edb \"{0}\" file failed", new object[]
                            {
                                this.OriginalEdbFilePath.PathName
                            });
                        }
                    }
                    if (flag4)
                    {
                        if (this.needReportProgress)
                        {
                            base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressDeletingLogFiles, 81);
                        }
                        base.WriteVerbose(Strings.VerboseDeleteDatabaseLogFiles(this.OwnerServer.Fqdn, this.OldLogFolderPath.PathName));
                        if (!WmiWrapper.DeleteFilesInDirectory(this.OwnerServer.Fqdn, this.OldLogFolderPath.PathName, new WmiWrapper.FileFilter(this.LogPathFilter)))
                        {
                            this.WriteWarning(Strings.FailedDeleteOldDatabaseLogFiles(this.OwnerServer.Fqdn, this.OldLogFolderPath.PathName));
                            TaskLogger.Trace("Failed to delete some of the orignal log files.", new object[0]);
                        }
                    }
                    if (this.moveCatalogs && SystemConfigurationTasksHelper.TryCreateDirectory(this.OwnerServer.Fqdn, this.targetCatalogsPath, null, new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), new Task.TaskWarningLoggingDelegate(this.WriteWarning)))
                    {
                        if (this.needReportProgress)
                        {
                            base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressCopyingCatalog, 87);
                        }
                        try
                        {
                            base.WriteVerbose(Strings.VerboseCopyDatabaseCatalogFiles(this.OwnerServer.Fqdn, this.originalCatalogsPath, this.targetCatalogsPath));
                            if (WmiWrapper.CopyFilesInDirectory(this.OwnerServer.Fqdn, this.originalCatalogsPath, this.targetCatalogsPath, new WmiWrapper.FileFilter(MoveDatabasePath.ReturnAllFiles)))
                            {
                                if (this.needReportProgress)
                                {
                                    base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressDeletingCatalog, 92);
                                }
                                base.WriteVerbose(Strings.VerboseDeleteDatabaseCatalogFiles(this.OwnerServer.Fqdn, this.originalCatalogsPath));
                                WmiWrapper.DeleteFilesInDirectory(this.OwnerServer.Fqdn, this.originalCatalogsPath, new WmiWrapper.FileFilter(MoveDatabasePath.ReturnAllFiles));
                                base.WriteVerbose(Strings.VerboseDeleteDirectory(this.OwnerServer.Fqdn, this.originalCatalogsPath));
                                WmiWrapper.RemoveDirectory(this.OwnerServer.Fqdn, this.originalCatalogsPath);
                            }
                        }
                        catch (ManagementException ex4)
                        {
                            TaskLogger.Trace("MoveDatabasePath raised exception {0} while moving catalog files", new object[]
                            {
                                ex4.ToString()
                            });
                            this.WriteWarning(Strings.ErrorMovingCatalogs(this.Identity.ToString(), ex4.Message));
                        }
                        catch (ArgumentException ex5)
                        {
                            TaskLogger.Trace("MoveDatabasePath raised exception {0} while moving catalog files", new object[]
                            {
                                ex5.ToString()
                            });
                            this.WriteWarning(Strings.ErrorMovingCatalogs(this.Identity.ToString(), ex5.Message));
                        }
                    }
                    this.SendNotificationRpcToReplayService();
                    flag5 = true;
                }
            }
            catch (WmiException ex6)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorFailedToConnectToServer(base.OwnerServerName, ex6.Message)), ErrorCategory.InvalidOperation, this.Identity);
            }
            catch (UnauthorizedAccessException ex7)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorFailedToConnectToServer(base.OwnerServerName, ex7.Message)), ErrorCategory.InvalidOperation, this.Identity);
            }
            finally
            {
                if (flag3)
                {
                    if (flag2 && !this.TryDeleteFile(this.TargetEdbFilePath.PathName))
                    {
                        this.WriteWarning(Strings.FailedToDeleteTempEdbFile(this.TargetEdbFilePath.PathName));
                        TaskLogger.Trace("MoveDatabasePath: delete edb \"{0}\" file failed", new object[]
                        {
                            this.TargetEdbFilePath.PathName
                        });
                    }
                    if (flag4)
                    {
                        TaskLogger.Trace("Error occurs when Copying path. delete copied log files", new object[0]);
                        base.WriteVerbose(Strings.VerboseDeleteDatabaseLogFiles(this.OwnerServer.Fqdn, this.LogFolderPath.PathName));
                        if (!WmiWrapper.DeleteFilesInDirectory(this.OwnerServer.Fqdn, this.LogFolderPath.PathName, new WmiWrapper.FileFilter(this.LogFileFilter)))
                        {
                            this.WriteWarning(Strings.FailedDeleteTempDatabaseLogFiles(base.OwnerServerName, this.LogFolderPath.PathName));
                            TaskLogger.Trace("Failed to delete some of the copied log files.", new object[0]);
                        }
                    }
                }
                if (!base.ConfigurationOnly && flag)
                {
                    if (this.needReportProgress)
                    {
                        base.WriteProgress(Strings.ProgressMoveDatabasePath(this.Identity.ToString()), Strings.ProgressRestoringDatabaseStatus, 95);
                    }
                    base.WriteVerbose(TaskVerboseStringHelper.GetReadObjectVerboseString(id, base.DataSession, typeof(Server)));
                    try
                    {
                        if (!flag5)
                        {
                            this.SendNotificationRpcToReplayService();
                            flag5 = true;
                        }
                        base.WriteVerbose(Strings.VerboseMountDatabase(this.Identity.ToString()));
                        AmRpcClientHelper.MountDatabase(ADObjectWrapperFactory.CreateWrapper(this.DataObject), 0, 0, 0);
                    }
                    catch (AmServerException ex8)
                    {
                        string message = ex8.Message;
                        TaskLogger.Trace("MoveDatabasePath.InternalProcessRecord raises exception while re-mounting Mdb status: {0}", new object[]
                        {
                            message
                        });
                        this.WriteWarning(Strings.ErrorFailedToRestoreDatabaseStatus(this.Identity.ToString(), message));
                    }
                    catch (AmServerTransientException ex9)
                    {
                        string message2 = ex9.Message;
                        TaskLogger.Trace("MoveDatabasePath.InternalProcessRecord raises exception while re-mounting Mdb status: {0}", new object[]
                        {
                            message2
                        });
                        this.WriteWarning(Strings.ErrorFailedToRestoreDatabaseStatus(this.Identity.ToString(), message2));
                    }
                }
                TaskLogger.LogExit();
            }
        }
Пример #17
0
        protected override void InternalValidate()
        {
            TaskLogger.LogEnter();
            base.InternalValidate();
            if (this.OwnerServer == null)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorDBOwningServerNotFound(this.DataObject.Identity.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
            }
            base.VerifyIsWithinScopes((IConfigurationSession)base.DataSession, this.OwnerServer, true, new DataAccessTask <Database> .ADObjectOutOfScopeString(Strings.ErrorServerOutOfScope));
            if (this.DataObject != null)
            {
                MapiTaskHelper.VerifyDatabaseAndItsOwningServerInScope(base.SessionSettings, this.DataObject, new Task.ErrorLoggerDelegate(base.WriteError));
            }
            ADObjectId adobjectId = new ADObjectId(this.OwnerServer.Guid);

            if (null == this.EdbFilePath && (base.Fields.IsModified("EdbFilePath") || base.Fields.IsChanged("EdbFilePath")))
            {
                base.WriteError(new ArgumentException(Strings.ErrorInvalidParameterValue("EdbFilePath", "null"), "EdbFilePath"), ErrorCategory.InvalidArgument, this.Identity);
            }
            if (!this.IsEdbFilePathChanged && !this.isLogFolderPathChanged)
            {
                this.WriteWarning(Strings.FileLocationNotChanged);
                TaskLogger.LogExit();
                return;
            }
            this.needReportProgress = !base.ConfigurationOnly;
            this.shouldContinueToDoConfigurationOnly = true;
            try
            {
                QueryFilter            filter     = new ComparisonFilter(ComparisonOperator.NotEqual, ADObjectSchema.Guid, this.DataObject.Guid);
                ADObjectId             rootId     = this.DataObject.IsExchange2009OrLater ? this.DataObject.AdministrativeGroup.GetChildId("Databases") : this.DataObject.Server;
                IEnumerable <Database> collection = base.DataSession.FindPaged <Database>(filter, rootId, true, null, 0);
                List <Database>        databases  = new List <Database>(collection);
                if (this.IsEdbFilePathChanged)
                {
                    if (this.DataObject.IsExchange2009OrLater)
                    {
                        base.WriteVerbose(Strings.VerboseEdbFileLocationUniqueUnderDAGCondition(this.EdbFilePath.PathName));
                        ADObjectId[] serversId;
                        if (this.DataObject.Servers != null && this.DataObject.Servers.Length != 0)
                        {
                            serversId = this.DataObject.Servers;
                        }
                        else
                        {
                            serversId = new ADObjectId[]
                            {
                                this.DataObject.Server
                            };
                        }
                        if (!new EdbFileLocationUniqueUnderDAGCondition(this.EdbFilePath.PathName, adobjectId, serversId, databases).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorEdbFileLocationNotUniqueUnderSameDAG(this.EdbFilePath.PathName), "EdbFilePath"), ErrorCategory.InvalidArgument, this.Identity);
                        }
                    }
                    else
                    {
                        base.WriteVerbose(Strings.VerboseEdbFileLocationUniqueUnderServerCondition(base.OwnerServerName, this.EdbFilePath.PathName));
                        if (!new EdbFileLocationUniqueUnderServerCondition(this.EdbFilePath.PathName, adobjectId, databases).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorEdbFileLocationNotUniqueUnderSameNode(this.EdbFilePath.PathName, base.OwnerServerName), "EdbFilePath"), ErrorCategory.InvalidArgument, this.Identity);
                        }
                    }
                }
                if (this.isLogFolderPathChanged)
                {
                    if (this.DataObject.IsExchange2009OrLater)
                    {
                        ADObjectId[] serversId2;
                        if (this.DataObject.Servers != null && this.DataObject.Servers.Length != 0)
                        {
                            serversId2 = this.DataObject.Servers;
                        }
                        else
                        {
                            serversId2 = new ADObjectId[]
                            {
                                this.DataObject.Server
                            };
                        }
                        if (!new DbLogLocationUniqueUnderDAGCondition(this.LogFolderPath.PathName, adobjectId, serversId2, databases).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorLogFolderPathNotUniqueUnderSameDAG(this.LogFolderPath.PathName), "LogFolderPath"), ErrorCategory.InvalidArgument, this.DataObject.Identity);
                        }
                    }
                    else if (!new DbLogLocationUniqueUnderServerCondition(this.LogFolderPath.PathName, adobjectId, databases).Verify())
                    {
                        base.WriteError(new ArgumentException(Strings.ErrorLogFolderPathNotUniqueUnderTheSameNode(this.LogFolderPath.PathName, base.OwnerServerName), "LogFolderPath"), ErrorCategory.InvalidArgument, this.DataObject.Identity);
                    }
                }
                if (base.ConfigurationOnly)
                {
                    this.moveCatalogs = false;
                    if (!this.Force && !(this.shouldContinueToDoConfigurationOnly = base.ShouldContinue(Strings.WarningUseConfigurationOnly)))
                    {
                        TaskLogger.LogExit();
                        return;
                    }
                    if (this.IsEdbFilePathChanged)
                    {
                        base.WriteVerbose(Strings.VerboseCheckFileExistenceCondition(base.OwnerServerName, this.TargetEdbFilePath.PathName));
                        if (new FileNotExistCondition(this.OwnerServer.Fqdn, this.TargetEdbFilePath.PathName).Verify())
                        {
                            this.WriteWarning(Strings.WarningEdbFileLocationNotExists(this.EdbFilePath.PathName));
                        }
                    }
                    TaskLogger.LogExit();
                    return;
                }
                else
                {
                    if (this.needReportProgress)
                    {
                        base.WriteProgress(Strings.ProgressValidatingFileLocations, Strings.ProgressMoveDatabasePath(this.Identity.ToString()), 5);
                    }
                    if (this.IsEdbFilePathChanged)
                    {
                        if (this.OriginalEdbFilePath == null)
                        {
                            base.WriteError(new InvalidOperationException(Strings.ErrorOriginalEdbFilePathMissed(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.Identity);
                        }
                        if (this.IsDatabaseFilesCreated)
                        {
                            base.WriteVerbose(Strings.VerboseCheckFileExistenceCondition(base.OwnerServerName, this.OriginalEdbFilePath.PathName));
                            if (new FileNotExistCondition(this.OwnerServer.Fqdn, this.OriginalEdbFilePath.PathName).Verify())
                            {
                                base.WriteError(new InvalidOperationException(Strings.ErrorSourceFileNotFound(base.OwnerServerName, this.OriginalEdbFilePath.PathName)), ErrorCategory.InvalidOperation, this.Identity);
                            }
                        }
                        base.WriteVerbose(Strings.VerbosePathOnFixedOrNetworkDriveCondition(base.OwnerServerName, this.EdbFilePath.PathName));
                        if (!new PathOnFixedOrNetworkDriveCondition(this.OwnerServer.Fqdn, this.EdbFilePath.PathName).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorEdbFileLocationNotOnFixedDrive(this.EdbFilePath.PathName), "EdbFilePath"), ErrorCategory.InvalidArgument, this.Identity);
                        }
                        base.WriteVerbose(Strings.VerboseCheckFileExistenceCondition(base.OwnerServerName, this.EdbFilePath.PathName));
                        if (!new FileNotExistCondition(this.OwnerServer.Fqdn, this.EdbFilePath.PathName).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorEdbFilePathOccupiedByFile(this.EdbFilePath.PathName, base.OwnerServerName), "EdbFilePath"), ErrorCategory.InvalidArgument, this.Identity);
                        }
                        base.WriteVerbose(Strings.VerboseCheckDirectoryExistenceCondition(base.OwnerServerName, this.EdbFilePath.PathName));
                        if (!new DirectoryNotExistCondition(this.OwnerServer.Fqdn, this.EdbFilePath.PathName).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorEdbFilePathOccupiedByDirectory(this.EdbFilePath.PathName, base.OwnerServerName), "EdbFilePath"), ErrorCategory.InvalidArgument, this.Identity);
                        }
                        string directoryName = Path.GetDirectoryName(this.EdbFilePath.PathName);
                        if (this.IsDatabaseFilesCreated && !SystemConfigurationTasksHelper.TryCreateDirectory(this.OwnerServer.Fqdn, directoryName, Database_Directory.GetDomainWidePermissions(), new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), new Task.TaskWarningLoggingDelegate(this.WriteWarning)))
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorEdbFileDirectoryNotExist(directoryName, base.OwnerServerName), "EdbFilePath"), ErrorCategory.InvalidOperation, this.Identity);
                        }
                        if (this.moveCatalogs)
                        {
                            this.moveCatalogs = this.DataObject.ObjectClass.Contains("msExchPrivateMDB");
                            if (this.moveCatalogs)
                            {
                                string directoryName2 = Path.GetDirectoryName(this.OriginalEdbFilePath.PathName);
                                this.originalCatalogsPath = this.GenerateCatalogPath(directoryName2, this.DataObject.Guid);
                                base.WriteVerbose(Strings.VerboseCheckDirectoryExistenceCondition(base.OwnerServerName, this.originalCatalogsPath));
                                this.moveCatalogs = WmiWrapper.IsDirectoryExisting(this.OwnerServer.Fqdn, this.originalCatalogsPath);
                                if (this.moveCatalogs)
                                {
                                    string directoryName3 = Path.GetDirectoryName(this.EdbFilePath.PathName);
                                    this.targetCatalogsPath = this.GenerateCatalogPath(directoryName3, this.DataObject.Guid);
                                    this.moveCatalogs       = (this.originalCatalogsPath != this.targetCatalogsPath);
                                }
                            }
                        }
                    }
                    else
                    {
                        this.moveCatalogs = false;
                    }
                    if (base.ConfigurationOnly)
                    {
                        TaskLogger.LogExit();
                        return;
                    }
                    if (this.isLogFolderPathChanged)
                    {
                        if (this.OldLogFolderPath == null)
                        {
                            base.WriteError(new InvalidOperationException(Strings.ErrorOriginalLogFolderPathIsMissed(this.Identity.ToString())), ErrorCategory.InvalidOperation, this.DataObject.Identity);
                        }
                        base.WriteVerbose(Strings.VerbosePathOnFixedOrNetworkDriveCondition(this.OwnerServer.Fqdn, this.LogFolderPath.PathName));
                        if (!new PathOnFixedOrNetworkDriveCondition(this.OwnerServer.Fqdn, this.LogFolderPath.PathName).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorPathIsNotOnFixedDrive("LogFolderPath")), ErrorCategory.InvalidArgument, this.DataObject.Identity);
                        }
                        base.WriteVerbose(Strings.VerboseLogLocationAvailableCondition(this.OwnerServer.Fqdn, this.LogFolderPath.PathName));
                        if (!new LogLocationAvailableCondition(this.OwnerServer.Fqdn, this.LogFolderPath.PathName, this.DataObject.LogFilePrefix).Verify())
                        {
                            base.WriteError(new ArgumentException(Strings.ErrorLogFolderPathNotAvailable, "LogFolderPath"), ErrorCategory.InvalidArgument, this.DataObject.Identity);
                        }
                        base.WriteVerbose(Strings.VerboseCheckLogFileExistingInPath(this.OwnerServer.Fqdn, this.oldLogFolderPath.PathName));
                        if (!WmiWrapper.IsFileExistingInPath(this.OwnerServer.Fqdn, this.oldLogFolderPath.PathName, new WmiWrapper.FileFilter(this.LogFileFilter)))
                        {
                            base.WriteError(new InvalidOperationException(Strings.ErrorMoveDatabasePathAsSourceFileNotExist(this.oldLogFolderPath.PathName)), ErrorCategory.InvalidOperation, this.DataObject.Identity);
                        }
                    }
                }
            }
            catch (WmiException ex)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorFailedToConnectToServer(base.OwnerServerName, ex.Message)), ErrorCategory.InvalidOperation, this.Identity);
            }
            catch (UnauthorizedAccessException ex2)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorFailedToConnectToServer(base.OwnerServerName, ex2.Message)), ErrorCategory.InvalidOperation, this.Identity);
            }
            if (this.DataObject.ReplicationType == ReplicationType.Remote && !this.DataObject.Recovery)
            {
                base.WriteError(new InvalidOperationException(Strings.ErrorMoveDatabasePathInvalidOnReplicated), ErrorCategory.InvalidOperation, this.DataObject.Identity);
            }
            TaskLogger.LogExit();
        }
Пример #18
0
        public static IEnumerable <CachedRDPConnection> Get_WMIRegCachedRDPConnection(Args_Get_WMIRegCachedRDPConnection args = null)
        {
            if (args == null)
            {
                args = new Args_Get_WMIRegCachedRDPConnection();
            }

            var FoundConnections = new List <CachedRDPConnection>();

            foreach (var Computer in args.ComputerName)
            {
                // HKEY_USERS
                var HKU = 2147483651;

                try
                {
                    var Reg = WmiWrapper.GetClass($@"\\{Computer}\ROOT\DEFAULT", "StdRegProv", args.Credential);

                    // extract out the SIDs of domain users in this hive
                    var outParams = WmiWrapper.CallMethod(Reg, "EnumKey", new Dictionary <string, object> {
                        { "hDefKey", HKU }, { "sSubKeyName", "" }
                    }) as System.Management.ManagementBaseObject;
                    var names = outParams["sNames"] as IEnumerable <string>;
                    if (names == null)
                    {
                        continue;
                    }

                    var UserSIDs = names.Where(x => x.IsRegexMatch($@"S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$"));

                    foreach (var UserSID in UserSIDs)
                    {
                        try
                        {
                            var UserName = ConvertFromSID.ConvertFrom_SID(new Args_ConvertFrom_SID {
                                ObjectSID = new[] { UserSID }, Credential = args.Credential
                            }).FirstOrDefault();

                            // pull out all the cached RDP connections
                            outParams = WmiWrapper.CallMethod(Reg, "EnumValues", new Dictionary <string, object> {
                                { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Software\Microsoft\Terminal Server Client\Default" }
                            }) as System.Management.ManagementBaseObject;
                            var ConnectionKeys = outParams["sNames"] as IEnumerable <string>;

                            if (ConnectionKeys != null)
                            {
                                foreach (var Connection in ConnectionKeys)
                                {
                                    // make sure this key is a cached connection
                                    if (Connection.IsRegexMatch(@"MRU.*"))
                                    {
                                        outParams = WmiWrapper.CallMethod(Reg, "GetStringValue", new Dictionary <string, object> {
                                            { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Software\Microsoft\Terminal Server Client\Default" }, { "sValueName", Connection }
                                        }) as System.Management.ManagementBaseObject;
                                        var TargetServer = outParams["sValue"] as string;

                                        var FoundConnection = new CachedRDPConnection
                                        {
                                            ComputerName = Computer,
                                            UserName     = UserName,
                                            UserSID      = UserSID,
                                            TargetServer = TargetServer,
                                            UsernameHint = null
                                        };
                                        FoundConnections.Add(FoundConnection);
                                    }
                                }
                            }

                            // pull out all the cached server info with username hints
                            outParams = WmiWrapper.CallMethod(Reg, "EnumKey", new Dictionary <string, object> {
                                { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Software\Microsoft\Terminal Server Client\Servers" }
                            }) as System.Management.ManagementBaseObject;
                            var ServerKeys = outParams["sNames"] as IEnumerable <string>;

                            if (ServerKeys != null)
                            {
                                foreach (var Server in ServerKeys)
                                {
                                    outParams = WmiWrapper.CallMethod(Reg, "GetStringValue", new Dictionary <string, object> {
                                        { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Software\Microsoft\Terminal Server Client\Servers\{Server}" }, { "sValueName", "UsernameHint" }
                                    }) as System.Management.ManagementBaseObject;
                                    var UsernameHint = outParams["sValue"] as string;

                                    var FoundConnection = new CachedRDPConnection
                                    {
                                        ComputerName = Computer,
                                        UserName     = UserName,
                                        UserSID      = UserSID,
                                        TargetServer = Server,
                                        UsernameHint = UsernameHint
                                    };
                                    FoundConnections.Add(FoundConnection);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Write_Verbose($@"[Get-WMIRegCachedRDPConnection] Error: {e}");
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Write_Warning($@"[Get-WMIRegCachedRDPConnection] Error accessing {Computer}, likely insufficient permissions or firewall rules on host: {e}");
                }
            }
            return(FoundConnections);
        }
        public static bool TryCreateDirectory(string serverFQDN, string directoryPath, FileSystemAccessRule[] directoryPermissions, Task.TaskVerboseLoggingDelegate verboseDelegate, Task.TaskWarningLoggingDelegate warningDelegate)
        {
            bool flag = false;

            if (string.Compare(serverFQDN, NativeHelpers.GetLocalComputerFqdn(false), StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                try
                {
                    verboseDelegate(Strings.VerboseCheckDirectoryExistenceCondition(serverFQDN, directoryPath));
                    if (Directory.Exists(directoryPath))
                    {
                        if (directoryPermissions != null)
                        {
                            DirectorySecurity directorySecurity = SystemConfigurationTasksHelper.CreateDirectorySecurityHelper(directoryPermissions);
                            directorySecurity.SetAccessRuleProtection(true, false);
                            verboseDelegate(Strings.VerboseSetAccessControl(serverFQDN, directoryPath));
                            TaskLogger.Trace("Directory \"" + directoryPath + "\" already exists on the local machine, just set the access control.", new object[0]);
                            Directory.SetAccessControl(directoryPath, directorySecurity);
                            flag = true;
                        }
                        else
                        {
                            verboseDelegate(Strings.VerboseNoAccessControlSpecified(serverFQDN, directoryPath));
                            TaskLogger.Trace("No access control specified to be set on directory \"" + directoryPath + "\".", new object[0]);
                            flag = true;
                        }
                    }
                    else if (directoryPermissions != null)
                    {
                        DirectorySecurity directorySecurity = SystemConfigurationTasksHelper.CreateDirectorySecurityHelper(directoryPermissions);
                        directorySecurity.SetAccessRuleProtection(true, false);
                        verboseDelegate(Strings.VerboseCreateDirectory(serverFQDN, directoryPath));
                        TaskLogger.Trace("Directory \"" + directoryPath + "\" does not exist.  Create the directory on the local machine and set the access control.", new object[0]);
                        Directory.CreateDirectory(directoryPath, directorySecurity);
                        flag = true;
                    }
                    else
                    {
                        verboseDelegate(Strings.VerboseCreateDirectory(serverFQDN, directoryPath));
                        verboseDelegate(Strings.VerboseNoAccessControlSpecified(serverFQDN, directoryPath));
                        TaskLogger.Trace("Directory \"" + directoryPath + "\" does not exist.  Create the directory on the local machine.  No access controls specified to set on the directory.", new object[0]);
                        Directory.CreateDirectory(directoryPath);
                        flag = true;
                    }
                    goto IL_43C;
                }
                catch (NotSupportedException ex)
                {
                    verboseDelegate(Strings.VerboseFailedCreateDirectory(serverFQDN, directoryPath, ex.Message));
                    TaskLogger.Trace("this.TryCreateDirectory() raised exception: {0}", new object[]
                    {
                        ex.ToString()
                    });
                    goto IL_43C;
                }
                catch (ArgumentNullException ex2)
                {
                    verboseDelegate(Strings.VerboseFailedCreateDirectory(serverFQDN, directoryPath, ex2.Message));
                    TaskLogger.Trace("this.TryCreateDirectory() raised exception: {0}", new object[]
                    {
                        ex2.ToString()
                    });
                    goto IL_43C;
                }
                catch (UnauthorizedAccessException ex3)
                {
                    verboseDelegate(Strings.VerboseFailedCreateDirectory(serverFQDN, directoryPath, ex3.Message));
                    TaskLogger.Trace("this.TryCreateDirectory() raised exception: {0}", new object[]
                    {
                        ex3.ToString()
                    });
                    goto IL_43C;
                }
                catch (ArgumentException ex4)
                {
                    verboseDelegate(Strings.VerboseFailedCreateDirectory(serverFQDN, directoryPath, ex4.Message));
                    TaskLogger.Trace("this.TryCreateDirectory() raised exception: {0}", new object[]
                    {
                        ex4.ToString()
                    });
                    goto IL_43C;
                }
                catch (IOException ex5)
                {
                    verboseDelegate(Strings.VerboseFailedCreateDirectory(serverFQDN, directoryPath, ex5.Message));
                    TaskLogger.Trace("this.TryCreateDirectory() raised exception: {0}", new object[]
                    {
                        ex5.ToString()
                    });
                    goto IL_43C;
                }
            }
            try
            {
                verboseDelegate(Strings.VerboseCheckDirectoryExistenceCondition(serverFQDN, directoryPath));
                uint num;
                if (!WmiWrapper.IsDirectoryExisting(serverFQDN, directoryPath))
                {
                    verboseDelegate(Strings.VerboseCreateDirectory(serverFQDN, directoryPath));
                    TaskLogger.Trace(string.Concat(new string[]
                    {
                        "Create the directory \"",
                        directoryPath,
                        "\" on the remote machine \"",
                        serverFQDN,
                        "\"."
                    }), new object[0]);
                    num = WmiWrapper.CreateDirectory(serverFQDN, directoryPath);
                }
                else
                {
                    num = 0U;
                }
                if (num == 0U)
                {
                    if (directoryPermissions != null)
                    {
                        verboseDelegate(Strings.VerboseSetAccessControl(serverFQDN, directoryPath));
                        TaskLogger.Trace(string.Concat(new string[]
                        {
                            "Set the access control for directory \"",
                            directoryPath,
                            "\" on the remote machine \"",
                            serverFQDN,
                            "\"."
                        }), new object[0]);
                        num = WmiWrapper.ChangeSecurityPermissions(serverFQDN, directoryPath, directoryPermissions);
                        if (num == 0U)
                        {
                            flag = true;
                        }
                        else
                        {
                            verboseDelegate(Strings.VerboseFailedSetAccessControl(serverFQDN, directoryPath, "WMI Status: " + num.ToString()));
                            TaskLogger.Trace("this.TryCreateDirectory() failed to set the access control on the directory - WMI Status: {0}", new object[]
                            {
                                num.ToString()
                            });
                        }
                    }
                    else
                    {
                        verboseDelegate(Strings.VerboseNoAccessControlSpecified(serverFQDN, directoryPath));
                        TaskLogger.Trace("No access control specified to be set on directory \"" + directoryPath + "\".", new object[0]);
                        flag = true;
                    }
                }
                else
                {
                    verboseDelegate(Strings.VerboseFailedCreateDirectory(serverFQDN, directoryPath, "WMI Status: " + num.ToString()));
                    TaskLogger.Trace("this.TryCreateDirectory() failed to create the directory - WMI Status: {0}", new object[]
                    {
                        num.ToString()
                    });
                }
            }
            catch (WmiException ex6)
            {
                verboseDelegate(Strings.VerboseFailedCreateDirectory(serverFQDN, directoryPath, ex6.Message));
                TaskLogger.Trace("this.TryCreateDirectory() raised exception: {0}", new object[]
                {
                    ex6.ToString()
                });
            }
            catch (UnauthorizedAccessException ex7)
            {
                verboseDelegate(Strings.ErrorFailedToConnectToServer(serverFQDN, ex7.Message));
                TaskLogger.Trace("this.TryCreateDirectory() raised exception: {0}", new object[]
                {
                    ex7.ToString()
                });
            }
IL_43C:
            if (!flag)
            {
                warningDelegate(Strings.WarningFailedCreateDirectory(serverFQDN, directoryPath));
            }
            return(flag);
        }
Пример #20
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     try
     {
         Dictionary <ServerRole, List <string> > dictionary  = new Dictionary <ServerRole, List <string> >();
         Dictionary <ServerRole, List <string> > dictionary2 = new Dictionary <ServerRole, List <string> >();
         foreach (TestServiceHealth.MonitoredService monitoredService in this.monitoredServicesArray)
         {
             if ((monitoredService.Roles & this.serverRolesBitfield) != ServerRole.None)
             {
                 try
                 {
                     using (ManagementObject serviceObject = WmiWrapper.GetServiceObject(this.serverName, monitoredService.Name))
                     {
                         if (serviceObject != null)
                         {
                             string strA = serviceObject["State"] as string;
                             if (string.Compare(strA, "Running", true, CultureInfo.InvariantCulture) == 0)
                             {
                                 using (List <ServerRole> .Enumerator enumerator = this.serverRolesList.GetEnumerator())
                                 {
                                     while (enumerator.MoveNext())
                                     {
                                         ServerRole serverRole = enumerator.Current;
                                         if ((monitoredService.Roles & serverRole) != ServerRole.None)
                                         {
                                             List <string> list = null;
                                             if (!dictionary2.TryGetValue(serverRole, out list))
                                             {
                                                 list = new List <string>();
                                                 dictionary2[serverRole] = list;
                                             }
                                             list.Add(monitoredService.Name);
                                         }
                                     }
                                     goto IL_18C;
                                 }
                             }
                             string strA2 = serviceObject["StartMode"] as string;
                             if (string.Compare(strA2, "Auto", true, CultureInfo.InvariantCulture) == 0 || monitoredService.IsRequired)
                             {
                                 foreach (ServerRole serverRole2 in this.serverRolesList)
                                 {
                                     if ((serverRole2 & monitoredService.Roles) != ServerRole.None)
                                     {
                                         List <string> list2 = null;
                                         if (!dictionary.TryGetValue(serverRole2, out list2))
                                         {
                                             list2 = new List <string>();
                                             dictionary[serverRole2] = list2;
                                         }
                                         list2.Add(monitoredService.Name);
                                     }
                                 }
                             }
                             IL_18C :;
                         }
                     }
                 }
                 catch (WmiException ex)
                 {
                     ServiceHealthWmiFailureException exception = new ServiceHealthWmiFailureException(ex.Message, ex);
                     base.WriteError(exception, ErrorCategory.ReadError, null);
                 }
             }
         }
         foreach (ServerRole serverRole3 in this.serverRolesList)
         {
             List <string> list3 = null;
             List <string> list4 = null;
             string[]      servicesRunning;
             if (dictionary2.TryGetValue(serverRole3, out list3))
             {
                 servicesRunning = list3.ToArray();
             }
             else
             {
                 servicesRunning = new string[0];
             }
             ExchangeServicesStatus sendToPipeline;
             if (dictionary.TryGetValue(serverRole3, out list4))
             {
                 string[] array2 = list4.ToArray();
                 this.monitoringData.Events.Add(new MonitoringEvent("MSExchange Monitoring ServiceHealth", (int)(11000 + serverRole3), EventTypeEnumeration.Error, Strings.SomeEssentialServicesForTheRoleNotRunning(MpServerRoles.DisplayRoleName(serverRole3), string.Join("\n", array2))));
                 sendToPipeline = new ExchangeServicesStatus(serverRole3, false, array2, servicesRunning);
             }
             else
             {
                 this.monitoringData.Events.Add(new MonitoringEvent("MSExchange Monitoring ServiceHealth", (int)(12000 + serverRole3), EventTypeEnumeration.Information, Strings.AllEssentialServicesForTheRoleRunning(MpServerRoles.DisplayRoleName(serverRole3))));
                 sendToPipeline = new ExchangeServicesStatus(serverRole3, true, new string[0], servicesRunning);
             }
             base.WriteObject(sendToPipeline);
         }
         this.monitoringData.Events.Add(new MonitoringEvent("MSExchange Monitoring ServiceHealth", 10000, EventTypeEnumeration.Information, Strings.NoMonitoringErrorsInTestServiceHealthTask));
     }
     finally
     {
         if (this.MonitoringContext)
         {
             base.WriteObject(this.monitoringData);
         }
         TaskLogger.LogExit();
     }
 }
 public override bool Verify()
 {
     return((this.Path.Length >= "\\\\.\\".Length && this.Path.StartsWith("\\\\.\\")) || WmiWrapper.IsDirectoryExisting(this.ServerName, this.Path));
 }
Пример #22
0
        public bool Initialize()
        {
            if (this.m_witnessServer == null)
            {
                List <string> frontendTransportServersInLocalSite = ReplayConfiguration.GetFrontendTransportServersInLocalSite();
                if (frontendTransportServersInLocalSite != null && frontendTransportServersInLocalSite.Count > 0)
                {
                    foreach (string text in frontendTransportServersInLocalSite)
                    {
                        if (!this.ServerHasMailboxRole(text))
                        {
                            if (!FileShareWitnessServerName.TryParse(text, out this.m_witnessServer))
                            {
                                TaskLogger.Trace("Attempt to parse FrontendTransport server name {0} to its file share witness name failed.", new object[]
                                {
                                    text
                                });
                                break;
                            }
                            break;
                        }
                    }
                }
                if (this.m_witnessServer == null)
                {
                    this.m_initializationException = new DagFswUnableToDetermineFrontendTransportServerException();
                    throw this.m_initializationException;
                }
            }
            try
            {
                this.AssignWitnessServerFqdn();
            }
            catch (ArgumentException ex)
            {
                this.m_initializationException = new DagFswUnableToParseWitnessServerNameException(ex);
                throw this.m_initializationException;
            }
            catch (ErrorUnableToFindFqdnForHostADErrorException ex2)
            {
                this.m_initializationException = new DagFswUnableToParseWitnessServerNameException(ex2);
                throw this.m_initializationException;
            }
            string text2 = this.WitnessServer.DomainName;

            if (string.IsNullOrEmpty(text2))
            {
                int num = this.WitnessServerFqdn.IndexOf('.');
                if (num > -1)
                {
                    text2 = this.WitnessServerFqdn.Substring(num + 1);
                }
            }
            string arg = string.Format(FileShareWitness.s_dagShareNameFormat, this.m_dagName, text2);

            UncFileSharePath.TryParse(string.Format(FileShareWitness.s_uncPathFormat, this.WitnessServerFqdn, arg), out this.m_fileShareWitnessShare);
            if (this.m_witnessDirectory == null)
            {
                string text3 = WmiWrapper.TryGetSystemDrive(this.WitnessServerFqdn);
                if (text3 == null)
                {
                    this.m_initializationException = new DagFswUnableToBindWitnessDirectoryException(this.WitnessServerFqdn);
                    throw this.m_initializationException;
                }
                this.m_witnessDirectory = NonRootLocalLongFullPath.Parse(string.Format(FileShareWitness.s_defaultDirectoryFormat, text3, arg));
            }
            this.m_initialized = true;
            return(this.m_initialized);
        }
Пример #23
0
        public void Create()
        {
            FileShareWitnessCheckResult fileShareWitnessCheckResult = this.Check();

            if (fileShareWitnessCheckResult != FileShareWitnessCheckResult.FswOK)
            {
                FileSystemSecurity fileSystemSecurity = new DirectorySecurity();
                foreach (FileSystemAccessRule rule in this.AccessRules)
                {
                    fileSystemSecurity.AddAccessRule(rule);
                }
                switch (fileShareWitnessCheckResult)
                {
                case FileShareWitnessCheckResult.FswDoesNotExist:
                    try
                    {
                        TaskLogger.Trace("Attempting to create new witness share \\\\{0}\\{1}.", new object[]
                        {
                            this.WitnessServer,
                            this.ShareName
                        });
                        WmiWrapper.CreateDirectory(this.WitnessServerFqdn, this.WitnessDirectory.ToString());
                        int num;
                        NetShare.AddShare(string.Format(FileShareWitness.s_hostNameFormat, this.WitnessServerFqdn), null, this.ShareName, this.WitnessDirectory.ToString(), this.m_shareRemark, fileSystemSecurity.GetSecurityDescriptorBinaryForm(), out num);
                        this.m_existingShareRemark      = this.m_shareRemark;
                        this.m_shareType                = 0U;
                        this.m_sharePermissions         = 1;
                        this.m_shareMaxUses             = -1;
                        this.m_existingWitnessDirectory = this.WitnessDirectory;
                        this.m_existingSecurity         = fileSystemSecurity;
                        this.m_exists        = new bool?(true);
                        this.m_isJustCreated = true;
                        TaskLogger.Trace("Attempt to create new witness share \\\\{0}\\{1} succeeded.", new object[]
                        {
                            this.WitnessServer,
                            this.ShareName
                        });
                        return;
                    }
                    catch (WmiException ex)
                    {
                        throw new DagFswUnableToCreateWitnessDirectoryException(this.WitnessServerFqdn, this.WitnessDirectory.ToString(), ex);
                    }
                    catch (Win32Exception ex2)
                    {
                        throw new DagFswUnableToCreateWitnessShareException(this.WitnessServerFqdn, this.FileShareWitnessShare.ToString(), ex2);
                    }
                    break;

                case FileShareWitnessCheckResult.FswWrongDirectory:
                    goto IL_1C1;

                case FileShareWitnessCheckResult.FswWrongPermissions:
                    break;

                default:
                    return;
                }
                fileSystemSecurity = this.m_existingSecurity;
                foreach (FileSystemAccessRule rule2 in this.AccessRules)
                {
                    fileSystemSecurity.AddAccessRule(rule2);
                }
                try
                {
IL_1C1:
                    TaskLogger.Trace("Attempting to modify permissions on witness share \\\\{0}\\{1}.", new object[]
                    {
                        this.WitnessServer,
                        this.ShareName
                    });
                    NetShare.SetShareInfo(this.WitnessServerFqdn, this.ShareName, this.WitnessDirectory.ToString(), this.m_shareRemark, this.m_shareType, this.m_sharePermissions, -1, fileSystemSecurity.GetSecurityDescriptorBinaryForm());
                    this.m_existingWitnessDirectory = this.WitnessDirectory;
                    this.m_existingSecurity         = fileSystemSecurity;
                    this.m_shareMaxUses             = -1;
                    this.m_exists = new bool?(true);
                    TaskLogger.Trace("Attempt to modify permissions on witness share \\\\{0}\\{1} succeeded.", new object[]
                    {
                        this.WitnessServer,
                        this.ShareName
                    });
                }
                catch (Win32Exception ex3)
                {
                    throw new DagFswUnableToUpdateWitnessShareException(this.WitnessServerFqdn, this.FileShareWitnessShare.ToString(), ex3);
                }
            }
        }
Пример #24
0
        public static IEnumerable <RegMountedDrive> Get_WMIRegMountedDrive(Args_Get_WMIRegMountedDrive args = null)
        {
            if (args == null)
            {
                args = new Args_Get_WMIRegMountedDrive();
            }

            var MountedDrives = new List <RegMountedDrive>();

            foreach (var Computer in args.ComputerName)
            {
                // HKEY_USERS
                var HKU = 2147483651;
                try
                {
                    var Reg = WmiWrapper.GetClass($@"\\{Computer}\ROOT\DEFAULT", "StdRegProv", args.Credential);

                    // extract out the SIDs of domain users in this hive
                    var outParams = WmiWrapper.CallMethod(Reg, "EnumKey", new Dictionary <string, object> {
                        { "hDefKey", HKU }, { "sSubKeyName", "" }
                    }) as System.Management.ManagementBaseObject;
                    var names = outParams["sNames"] as IEnumerable <string>;
                    if (names == null)
                    {
                        continue;
                    }

                    var UserSIDs = names.Where(x => x.IsRegexMatch($@"S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$"));

                    foreach (var UserSID in UserSIDs)
                    {
                        try
                        {
                            var UserName = ConvertFromSID.ConvertFrom_SID(new Args_ConvertFrom_SID {
                                ObjectSID = new[] { UserSID }, Credential = args.Credential
                            }).FirstOrDefault();
                            outParams = WmiWrapper.CallMethod(Reg, "EnumKey", new Dictionary <string, object> {
                                { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Network" }
                            }) as System.Management.ManagementBaseObject;
                            var DriveLetters = outParams["sNames"] as IEnumerable <string>;
                            if (DriveLetters == null)
                            {
                                continue;
                            }

                            foreach (var DriveLetter in DriveLetters)
                            {
                                outParams = WmiWrapper.CallMethod(Reg, "GetStringValue", new Dictionary <string, object> {
                                    { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Network\{DriveLetter}" }, { "sValueName", "ProviderName" }
                                }) as System.Management.ManagementBaseObject;
                                var ProviderName = outParams["sValue"] as string;
                                outParams = WmiWrapper.CallMethod(Reg, "GetStringValue", new Dictionary <string, object> {
                                    { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Network\{DriveLetter}" }, { "sValueName", "RemotePath" }
                                }) as System.Management.ManagementBaseObject;
                                var RemotePath = outParams["sValue"] as string;
                                outParams = WmiWrapper.CallMethod(Reg, "GetStringValue", new Dictionary <string, object> {
                                    { "hDefKey", HKU }, { "sSubKeyName", $@"{UserSID}\Network\{DriveLetter}" }, { "sValueName", "UserName" }
                                }) as System.Management.ManagementBaseObject;
                                var DriveUserName = outParams["sValue"] as string;
                                if (UserName == null)
                                {
                                    UserName = "";
                                }

                                if (RemotePath != null && (RemotePath != ""))
                                {
                                    var MountedDrive = new RegMountedDrive
                                    {
                                        ComputerName  = Computer,
                                        UserName      = UserName,
                                        UserSID       = UserSID,
                                        DriveLetter   = DriveLetter,
                                        ProviderName  = ProviderName,
                                        RemotePath    = RemotePath,
                                        DriveUserName = DriveUserName
                                    };
                                    MountedDrives.Add(MountedDrive);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Write_Verbose($@"[Get-WMIRegMountedDrive] Error: {e}");
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Write_Warning($@"[Get-WMIRegMountedDrive] Error accessing {Computer}, likely insufficient permissions or firewall rules on host: {e}");
                }
            }
            return(MountedDrives);
        }
Пример #25
0
        public static IEnumerable <ProxySettings> Get_WMIRegProxy(Args_Get_WMIRegProxy args = null)
        {
            if (args == null)
            {
                args = new Args_Get_WMIRegProxy();
            }

            var ProxySettings = new List <ProxySettings>();

            foreach (var Computer in args.ComputerName)
            {
                try
                {
                    var RegProvider = WmiWrapper.GetClass($@"\\{Computer}\ROOT\DEFAULT", "StdRegProv", args.Credential);
                    var Key         = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings";

                    // HKEY_CURRENT_USER
                    var HKCU      = 2147483649;
                    var outParams = WmiWrapper.CallMethod(RegProvider, "GetStringValue", new Dictionary <string, object> {
                        { "hDefKey", HKCU }, { "sSubKeyName", Key }, { "sValueName", "ProxyServer" }
                    }) as System.Management.ManagementBaseObject;
                    var ProxyServer = outParams["sValue"] as string;
                    outParams = WmiWrapper.CallMethod(RegProvider, "GetStringValue", new Dictionary <string, object> {
                        { "hDefKey", HKCU }, { "sSubKeyName", Key }, { "sValueName", "AutoConfigURL" }
                    }) as System.Management.ManagementBaseObject;
                    var AutoConfigURL = outParams["sValue"] as string;

                    var Wpad = "";
                    if (AutoConfigURL != null && AutoConfigURL != "")
                    {
                        try
                        {
                            Wpad = (new System.Net.WebClient()).DownloadString(AutoConfigURL);
                        }
                        catch
                        {
                            Logger.Write_Warning($@"[Get-WMIRegProxy] Error connecting to AutoConfigURL : {AutoConfigURL}");
                        }
                    }

                    if (ProxyServer != null || AutoConfigURL != null)
                    {
                        var Out = new ProxySettings
                        {
                            ComputerName  = Computer,
                            ProxyServer   = ProxyServer,
                            AutoConfigURL = AutoConfigURL,
                            Wpad          = Wpad
                        };
                        ProxySettings.Add(Out);
                    }
                    else
                    {
                        Logger.Write_Warning($@"[Get-WMIRegProxy] No proxy settings found for {Computer}");
                    }
                }
                catch (Exception e)
                {
                    Logger.Write_Warning($@"[Get-WMIRegProxy] Error enumerating proxy settings for {Computer} : {e}");
                }
            }

            return(ProxySettings);
        }