コード例 #1
0
        /// <summary>
        /// Internal task execution code.
        /// </summary>
        /// <param name="environment">The script execution environment.</param>
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            // first check if the queue already exists
            if (MessageQueue.Exists(messageQueuePath))
            {
                if (mode == CreateMessageQueueMode.DoNothingIfExists)
                {
                    environment.LogMessage("Message queue '{0}' already exists, doing nothing.", messageQueuePath);
                    return;
                }

                if (mode == CreateMessageQueueMode.FailIfAlreadyExists)
                {
                    throw new RunnerFailedException(
                              String.Format(
                                  System.Globalization.CultureInfo.InvariantCulture,
                                  "Message queue '{0}' already exists.",
                                  messageQueuePath));
                }

                // otherwise delete the queue
                environment.LogMessage("Message queue '{0}' already exists, it will be deleted.", messageQueuePath);
                MessageQueue.Delete(messageQueuePath);
            }

            using (MessageQueue queue = MessageQueue.Create(messageQueuePath, isTransactional))
            {
                if (userName != null)
                {
                    queue.SetPermissions(userName, accessRights);
                }
            }
        }
コード例 #2
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;

                ApplicationPool appPoolToWorkOn = null;
                bool            updatedExisting = false;

                foreach (ApplicationPool applicationPool in applicationPoolCollection)
                {
                    if (applicationPool.Name == applicationPoolName)
                    {
                        if (mode == CreateApplicationPoolMode.DoNothingIfExists)
                        {
                            environment.LogMessage(
                                String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    "Application pool '{0}' already exists, doing nothing.",
                                    applicationPoolName));
                        }
                        else if (mode == CreateApplicationPoolMode.FailIfAlreadyExists)
                        {
                            throw new RunnerFailedException(
                                      String.Format(
                                          System.Globalization.CultureInfo.InvariantCulture,
                                          "Application '{0}' already exists.",
                                          applicationPoolName));
                        }

                        // otherwise we should update the existing application pool
                        appPoolToWorkOn = applicationPool;
                        updatedExisting = true;
                        break;
                    }
                }

                if (appPoolToWorkOn == null)
                {
                    appPoolToWorkOn = serverManager.ApplicationPools.Add(applicationPoolName);
                }

                appPoolToWorkOn.AutoStart             = false;
                appPoolToWorkOn.Enable32BitAppOnWin64 = true;
                appPoolToWorkOn.ManagedPipelineMode   =
                    ClassicManagedPipelineMode ? ManagedPipelineMode.Classic : ManagedPipelineMode.Integrated;
                //serverManager.ApplicationPools.Add(appPoolToWorkOn);
                serverManager.CommitChanges();

                environment.LogMessage(
                    String.Format(
                        System.Globalization.CultureInfo.InvariantCulture,
                        "Application pool '{0}' {1}.",
                        applicationPoolName,
                        updatedExisting ? "updated" : "created"));
            }
        }
コード例 #3
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;

                foreach (ApplicationPool applicationPool in applicationPoolCollection)
                {
                    if (applicationPool.Name == ApplicationPoolName)
                    {
                        switch (action)
                        {
                        case ControlApplicationPoolAction.Start:
                            RunWithRetries(x => applicationPool.Start(), 3);
                            break;

                        case ControlApplicationPoolAction.Stop:
                            RunWithRetries(x => applicationPool.Stop(), 3);
                            break;

                        case ControlApplicationPoolAction.Recycle:
                            RunWithRetries(x => applicationPool.Recycle(), 3);
                            break;

                        default:
                            throw new NotSupportedException();
                        }

                        serverManager.CommitChanges();

                        environment.LogMessage(
                            String.Format(
                                System.Globalization.CultureInfo.InvariantCulture,
                                "Application pool '{0}' has been deleted.",
                                ApplicationPoolName));

                        return;
                    }
                }

                string message = String.Format(
                    System.Globalization.CultureInfo.InvariantCulture,
                    "Application pool '{0}' does not exist.",
                    applicationPoolName);

                if (failIfNotExist)
                {
                    throw new RunnerFailedException(message);
                }

                environment.LogMessage(message);
            }
        }
コード例 #4
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            using (DirectoryEntry computerDirectoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
            {
                using (DirectoryEntry userEntry = computerDirectoryEntry.Children.Find(userName, "user"))
                {
                    using (DirectoryEntry grp = computerDirectoryEntry.Children.Find(group, "group"))
                    {
                        try
                        {
                            grp.Invoke("Add", new object[] { userEntry.Path.ToString() });
                        }
                        catch (TargetInvocationException ex)
                        {
                            if (ex.InnerException is COMException)
                            {
                                if ((ex.InnerException as COMException).ErrorCode == -2147023518)
                                {
                                    // user is already member of the group, nothing to do
                                    environment.LogMessage(
                                        "User '{0}' is already member of the group '{1}', nothing to do.",
                                        userName,
                                        group);
                                    return;
                                }
                            }

                            throw;
                        }
                    }
                }
            }
        }
コード例 #5
0
        public static string GetIisVersion(IScriptExecutionEnvironment environment, bool failIfNotExist)
        {
            string major;

            if (environment.IsConfigSettingDefined(IisMajorVersion))
            {
                major = environment.GetConfigSetting(IisMajorVersion);
            }
            else
            {
                ExecuteTask(environment);
                major = environment.GetConfigSetting(IisMajorVersion);
            }

            if (string.IsNullOrEmpty(major))
            {
                const string Msg = "IIS not installed or IIS access denied!";
                if (failIfNotExist)
                {
                    throw new RunnerFailedException(Msg);
                }
                environment.LogMessage(Msg);

                return("0.0");
            }

            string minor = environment.GetConfigSetting(IisMinorVersion);

            return(major + "." + minor);
        }
コード例 #6
0
 protected override void DoExecute(IScriptExecutionEnvironment environment)
 {
     using (DirectoryEntry computerDirectoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
     {
         try
         {
             using (DirectoryEntry userEntry = computerDirectoryEntry.Children.Find(userName, "user"))
             {
                 computerDirectoryEntry.Children.Remove(userEntry);
             }
         }
         catch (COMException ex)
         {
             if (ex.ErrorCode == -2147022675)
             {
                 // if the user does not exist
                 environment.LogMessage(
                     "User '{0}' does not exist, nothing to do.",
                     userName);
                 return;
             }
             else
             {
                 throw;
             }
         }
     }
 }
コード例 #7
0
        private void CopyStructureRecursive(
            IScriptExecutionEnvironment environment,
            string sourcePathRecursive,
            string destinationPathRecursive,
            Regex inclusionRegex,
            Regex exclusionRegex)
        {
            if (exclusionRegex != null && exclusionRegex.IsMatch(sourcePathRecursive))
            {
                return;
            }

            DirectoryInfo info = new DirectoryInfo(sourcePathRecursive);

            foreach (FileSystemInfo fileSystemInfo in info.GetFileSystemInfos())
            {
                if (fileSystemInfo is FileInfo)
                {
                    if (inclusionRegex != null && false == inclusionRegex.IsMatch(fileSystemInfo.FullName))
                    {
                        continue;
                    }
                    if (exclusionRegex != null && exclusionRegex.IsMatch(fileSystemInfo.FullName))
                    {
                        continue;
                    }

                    FileInfo fileInfo = fileSystemInfo as FileInfo;
                    string   filePath = Path.Combine(destinationPathRecursive, fileInfo.Name);

                    if (false == Directory.Exists(destinationPathRecursive))
                    {
                        Directory.CreateDirectory(destinationPathRecursive);
                    }

                    fileInfo.CopyTo(filePath, overwriteExisting);
                    environment.LogMessage(
                        "Copied file '{0}' to '{1}'",
                        fileSystemInfo.FullName,
                        filePath);
                    copiedFilesList.Add(filePath);
                }
                else
                {
                    DirectoryInfo dirInfo          = fileSystemInfo as DirectoryInfo;
                    string        subdirectoryPath = Path.Combine(
                        destinationPathRecursive,
                        dirInfo.Name);
                    CopyStructureRecursive(
                        environment,
                        dirInfo.FullName,
                        subdirectoryPath,
                        inclusionRegex,
                        exclusionRegex);
                }
            }
        }
コード例 #8
0
 protected override void DoExecute(IScriptExecutionEnvironment environment)
 {
     Process[] processByName = Process.GetProcessesByName(processName);
     foreach (Process process in processByName)
     {
         environment.LogMessage("Killing process '{0}'", process.ProcessName);
         process.Kill();
     }
 }
コード例 #9
0
 protected override void DoExecute(IScriptExecutionEnvironment environment)
 {
     try
     {
         using (ServiceController serviceController = new ServiceController(serviceName))
         {
             // this should throw an exception if the service does not exist
             System.Runtime.InteropServices.SafeHandle serviceHandle = serviceController.ServiceHandle;
             environment.SetConfigSetting(configurationSetting, "true");
             environment.LogMessage("Windows service '{0}' exists.", serviceName);
         }
     }
     catch (InvalidOperationException)
     {
         environment.SetConfigSetting(configurationSetting, "false");
         environment.LogMessage(
             "Windows service '{0}' does not exist.",
             serviceName);
     }
 }
コード例 #10
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            using (ServerManager serverManager = new ServerManager())
            {
                Site site = serverManager.Sites["Default Web Site"];

                string      vdirPath       = "/" + ApplicationName;
                Application ourApplication = null;
                foreach (Application application in site.Applications)
                {
                    if (application.Path == vdirPath)
                    {
                        if (mode == CreateWebApplicationMode.DoNothingIfExists)
                        {
                            environment.LogMessage(
                                "Web application '{0}' already exists, doing nothing.",
                                applicationName);
                            return;
                        }

                        if (mode == CreateWebApplicationMode.FailIfAlreadyExists)
                        {
                            throw new RunnerFailedException(
                                      String.Format(
                                          System.Globalization.CultureInfo.InvariantCulture,
                                          "Web application '{0}' already exists.",
                                          applicationName));
                        }

                        // otherwise we should update the existing virtual directory
                        ourApplication = application;
                        break;
                    }
                }

                if (ourApplication == null)
                {
                    ourApplication = site.Applications.Add(vdirPath, LocalPath);
                }
                ourApplication.ApplicationPoolName = applicationPoolName;

                throw new NotImplementedException();
                //Microsoft.Web.Administration.Configuration configuration = ourApplication.GetWebConfiguration();
                ////ConfigurationSection webServerSection = configuration.GetSection("system.webServer");
                ////ConfigurationElement defaultDocEl = webServerSection.GetChildElement("defaultDocument");
                //ConfigurationElement defaultDocEl = configuration.GetSection("system.webServer/defaultDocument");
                //defaultDocEl["enabled"] = EnableDefaultDoc.ToString(CultureInfo.InvariantCulture);

                //serverManager.CommitChanges();
            }
        }
コード例 #11
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            ServerManager             serverManager             = new ServerManager();
            ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;

            foreach (ApplicationPool applicationPool in applicationPoolCollection)
            {
                if (applicationPool.Name == ApplicationPoolName)
                {
                    applicationPoolCollection.Remove(applicationPool);
                    serverManager.CommitChanges();

                    environment.LogMessage(
                        String.Format(
                            System.Globalization.CultureInfo.InvariantCulture,
                            "Application pool '{0}' has been deleted.",
                            ApplicationPoolName));

                    return;
                }
            }

            if (FailIfNotExist)
            {
                throw new RunnerFailedException(
                          String.Format(
                              CultureInfo.InvariantCulture,
                              "Application '{0}' does not exist.",
                              ApplicationPoolName));
            }

            environment.LogMessage(
                String.Format(
                    CultureInfo.InvariantCulture,
                    "Application pool '{0}' does not exist, doing nothing.",
                    ApplicationPoolName));
        }
コード例 #12
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
// ReSharper disable InconsistentNaming
            const int GenericWrite = 0x40000000;
// ReSharper restore InconsistentNaming
            IntPtr scHndl  = IntPtr.Zero;
            IntPtr svcHndl = IntPtr.Zero;

            try
            {
                scHndl = OpenSCManager(null, null, GenericWrite);
                if (scHndl == IntPtr.Zero)
                {
                    throw new RunnerFailedException("Service manager could not be opened!");
                }

// ReSharper disable InconsistentNaming
                const int Delete = 0x10000;
// ReSharper restore InconsistentNaming
                svcHndl = OpenService(scHndl, ServiceName, Delete);
                if (svcHndl == IntPtr.Zero)
                {
                    if (FailIfNotExist)
                    {
                        throw new RunnerFailedException("Service {0} does not exist.", ServiceName);
                    }

                    environment.LogMessage("Service '{0}' does not exist, doing nothing.", ServiceName);
                    return;
                }

                int result = DeleteService(svcHndl);
                if (result != 0)
                {
                    throw new RunnerFailedException("Uninstall windows service failed with error code:{0}", result);
                }
            }
            finally
            {
                if (svcHndl != IntPtr.Zero)
                {
                    CloseServiceHandle(svcHndl);
                }
                if (scHndl != IntPtr.Zero)
                {
                    CloseServiceHandle(scHndl);
                }
            }
        }
コード例 #13
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            SearchOption searchOption = SearchOption.TopDirectoryOnly;

            if (recursive)
            {
                searchOption = SearchOption.AllDirectories;
            }

            foreach (string file in Directory.GetFiles(directoryPath, filePattern, searchOption))
            {
                File.Delete(file);
                environment.LogMessage("Deleted file '{0}'", file);
            }
        }
コード例 #14
0
 /// <summary>
 /// Internal task execution code.
 /// </summary>
 /// <param name="environment">The script execution environment.</param>
 protected override void DoExecute(IScriptExecutionEnvironment environment)
 {
     // log important environment information
     environment.LogMessage("Machine name: {0}", Environment.MachineName);
     environment.LogMessage("OS Version: {0}", Environment.OSVersion);
     environment.LogMessage("User name: {0}", Environment.UserName);
     environment.LogMessage("User domain name: {0}", Environment.UserDomainName);
     environment.LogMessage("CLR version: {0}", Environment.Version);
     environment.LogMessage("Current directory: {0}", Environment.CurrentDirectory);
 }
コード例 #15
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            const string AppPoolsRootName = @"IIS://localhost/W3SVC/AppPools";

            using (DirectoryEntry parent = new DirectoryEntry(AppPoolsRootName))
            {
                DirectoryEntry applicationPoolEntry = null;

                try
                {
                    try
                    {
                        applicationPoolEntry = parent.Children.Find(ApplicationPoolName, "IIsApplicationPool");
                        applicationPoolEntry.DeleteTree();
                        applicationPoolEntry.CommitChanges();
                    }
                    catch (DirectoryNotFoundException)
                    {
                        // application pool already exists
                        if (FailIfNotExist)
                        {
                            throw new RunnerFailedException(
                                      String.Format(
                                          CultureInfo.InvariantCulture,
                                          "Application '{0}' does not exist.",
                                          ApplicationPoolName));
                        }

                        environment.LogMessage(
                            String.Format(
                                CultureInfo.InvariantCulture,
                                "Application pool '{0}' does not exist, doing nothing.",
                                ApplicationPoolName));
                        return;
                    }
                }
                finally
                {
                    if (applicationPoolEntry != null)
                    {
                        applicationPoolEntry.Dispose();
                    }
                }

                parent.CommitChanges();
            }
        }
コード例 #16
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            const string AppPoolsRootName = @"IIS://localhost/W3SVC/AppPools";

            using (DirectoryEntry parent = new DirectoryEntry(AppPoolsRootName))
            {
                DirectoryEntry applicationPoolEntry = null;

                try
                {
                    // first check if the user already exists
                    try
                    {
                        applicationPoolEntry = parent.Children.Find(applicationPoolName, "IIsApplicationPool");

                        applicationPoolEntry.Invoke(action.ToString());
                    }
                    catch (DirectoryNotFoundException)
                    {
                        string message = String.Format(
                            System.Globalization.CultureInfo.InvariantCulture,
                            "Application pool '{0}' does not exist.",
                            applicationPoolName);

                        if (failIfNotExist)
                        {
                            throw new RunnerFailedException(message);
                        }
                        else
                        {
                            environment.LogMessage(message);
                        }
                    }
                }
                finally
                {
                    if (applicationPoolEntry != null)
                    {
                        applicationPoolEntry.Dispose();
                    }
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Internal task execution code.
        /// </summary>
        /// <param name="environment">The script execution environment.</param>
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            XmlDocument xmlDoc = new XmlDocument();

            if (configurationString != null)
            {
                xmlDoc.LoadXml(configurationString);
            }
            else if (configurationFileName != null)
            {
                xmlDoc.Load(configurationFileName);
            }
            else
            {
                throw new RunnerFailedException("Either the configuration string or the configuration fileName has to be set.");
            }

            XmlNode configurationRootNode = xmlDoc.SelectSingleNode("Configuration");

            XmlNodeList nodes = xmlDoc.SelectNodes("Configuration//*");

            foreach (XmlNode node in nodes)
            {
                if (node.InnerText == node.InnerXml)
                {
                    StringBuilder settingName = new StringBuilder();
                    string        terminator  = null;
                    for (XmlNode parentNode = node; parentNode != null && parentNode != configurationRootNode; parentNode = parentNode.ParentNode)
                    {
                        settingName.Insert(0, terminator);
                        settingName.Insert(0, parentNode.Name);
                        terminator = "/";
                    }

                    environment.LogMessage(
                        "Configuration setting '{0}' has value '{1}'",
                        settingName,
                        node.InnerText);
                    environment.SetConfigSetting(settingName.ToString(), node.InnerText);
                }
            }
        }
コード例 #18
0
        //internal static int GetMinorVersion(string version)
        //{
        //    if (string.IsNullOrEmpty(version))
        //        return 0;
        //    string[] split = version.Split('.');
        //    return split.Length != 2 ? 0 : Convert.ToInt32(split[1], CultureInfo.InvariantCulture);
        //}

        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            GetRegistryValueTask innerTask = new GetRegistryValueTask(
                Microsoft.Win32.Registry.LocalMachine,
                @"SOFTWARE\Microsoft\InetStp",
                "MajorVersion",
                IisMajorVersion);

            innerTask.Execute(environment);

            innerTask = new GetRegistryValueTask(
                Microsoft.Win32.Registry.LocalMachine,
                @"SOFTWARE\Microsoft\InetStp",
                "MinorVersion",
                IisMinorVersion);
            innerTask.Execute(environment);

            environment.LogMessage(
                "Local IIS has version {0}.{1}",
                environment.GetConfigSetting("IIS/MajorVersion"),
                environment.GetConfigSetting("IIS/MinorVersion"));
        }
コード例 #19
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            using (FileStream zipFileStream = new FileStream(
                       zipFileName,
                       FileMode.Create,
                       FileAccess.ReadWrite,
                       FileShare.None))
            {
                using (ZipOutputStream zipStream = new ZipOutputStream(zipFileStream))
                {
                    if (compressionLevel.HasValue)
                    {
                        zipStream.SetLevel(compressionLevel.Value);
                    }

                    buffer = new byte[1024 * 1024];

                    foreach (string fileName in filesToZip)
                    {
                        int skipChar = 0;

                        if (false == String.IsNullOrEmpty(baseDir) &&
                            (baseDir[baseDir.Length - 1] == '\\' ||
                             baseDir[baseDir.Length - 1] == '/'))
                        {
                            skipChar++;
                        }

                        // cut off the leading part of the path (up to the root directory of the package)
                        string basedFileName = fileName.Substring(baseDir.Length + skipChar);

                        basedFileName = ZipEntry.CleanName(basedFileName);

                        environment.LogMessage("Zipping file '{0}'", basedFileName);
                        AddFileToZip(fileName, basedFileName, zipStream);
                    }
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// Internal task execution code.
        /// </summary>
        /// <param name="environment">The script execution environment.</param>
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            // first check if the queue already exists
            if (false == MessageQueue.Exists(MessageQueuePath))
            {
                if (FailIfNotExist)
                {
                    throw new RunnerFailedException(
                              String.Format(
                                  CultureInfo.InvariantCulture,
                                  "Message queue does not '{0}' exist.",
                                  MessageQueuePath));
                }

                environment.LogMessage(
                    String.Format(
                        CultureInfo.InvariantCulture,
                        "Message queue does not '{0}' exist, doing nothing.",
                        MessageQueuePath));
                return;
            }

            MessageQueue.Delete(MessageQueuePath);
        }
コード例 #21
0
 protected override void DoExecute(IScriptExecutionEnvironment environment)
 {
     environment.LogMessage(message);
 }
コード例 #22
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            string version = GetLocalIisVersionTask.GetIisVersion(environment, false);
            int    major   = GetLocalIisVersionTask.GetMajorVersion(version);

            if (major < 6 || major == 0)
            {
                environment.LogMessage("IIS does not support application pools.");
                return;
            }

            const string AppPoolsRootName = @"IIS://localhost/W3SVC/AppPools";

            using (DirectoryEntry parent = new DirectoryEntry(AppPoolsRootName))
            {
                DirectoryEntry applicationPoolEntry = null;

                try
                {
                    // first check if the user already exists
                    try
                    {
                        applicationPoolEntry = parent.Children.Find(applicationPoolName, "IIsApplicationPool");

                        // application pool already exists
                        if (mode == CreateApplicationPoolMode.DoNothingIfExists)
                        {
                            environment.LogMessage(
                                String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    "Application pool '{0}' already exists, doing nothing.",
                                    applicationPoolName));
                            return;
                        }
                        else if (mode == CreateApplicationPoolMode.FailIfAlreadyExists)
                        {
                            throw new RunnerFailedException(
                                      String.Format(
                                          System.Globalization.CultureInfo.InvariantCulture,
                                          "Application '{0}' already exists.",
                                          applicationPoolName));
                        }

                        // otherwise we should update the existing application pool
                    }
                    catch (DirectoryNotFoundException)
                    {
                        // application pool does not exist, go on and add it
                        applicationPoolEntry = parent.Children.Add(applicationPoolName, "IIsApplicationPool");
                    }

                    if (major > 6)
                    {
                        applicationPoolEntry.InvokeSet(
                            "ManagedPipelineMode",
                            new object[] { classicManagedPipelineMode ? 1 : 0 });
                    }

                    applicationPoolEntry.CommitChanges();
                }
                finally
                {
                    if (applicationPoolEntry != null)
                    {
                        applicationPoolEntry.Dispose();
                    }
                }

                parent.CommitChanges();
            }
        }
コード例 #23
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            string configSettingName = String.Format(
                System.Globalization.CultureInfo.InvariantCulture,
                "ServicesExist/{0}",
                serviceName);

            CheckIfServiceExistsTask.Execute(environment, serviceName, configSettingName);
            if (bool.Parse(environment.GetConfigSetting(configSettingName)) == false)
            {
                if (FailIfNotExist)
                {
                    throw new RunnerFailedException("Service {0} does not exist.", serviceName);
                }

                environment.LogMessage("Service '{0}' does not exist, doing nothing.", serviceName);
                return;
            }

            using (ServiceController serviceController = new ServiceController(serviceName, MachineName))
            {
                ServiceControllerStatus status = ServiceControllerStatus.Running;
                switch (mode)
                {
                case ControlWindowsServiceMode.Start:
                    status = ServiceControllerStatus.Running;
                    break;

                case ControlWindowsServiceMode.Stop:
                    status = ServiceControllerStatus.Stopped;
                    break;
                }

                switch (status)
                {
                case ServiceControllerStatus.Running:
                    if (serviceController.Status != ServiceControllerStatus.Running)
                    {
                        serviceController.Start();
                    }
                    break;

                case ServiceControllerStatus.Stopped:
                    if (serviceController.Status != ServiceControllerStatus.Stopped)
                    {
                        serviceController.Stop();
                    }
                    break;
                }

                int timeSoFar = 0;
                for (serviceController.Refresh(); serviceController.Status != status; serviceController.Refresh())
                {
                    System.Threading.Thread.Sleep(500);
                    timeSoFar += 500;

                    if (timeSoFar >= timeout.TotalMilliseconds)
                    {
                        throw new RunnerFailedException(
                                  String.Format(
                                      System.Globalization.CultureInfo.InvariantCulture,
                                      "Timeout waiting for '{0}' service to reach status {1}.",
                                      serviceName,
                                      status));
                    }
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Internal task execution code.
        /// </summary>
        /// <param name="environment">The script execution environment.</param>
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            string configSettingName = String.Format(
                System.Globalization.CultureInfo.InvariantCulture,
                "ServicesExist/{0}",
                serviceName);

            CheckIfServiceExistsTask checkIfServiceExistsTask = new CheckIfServiceExistsTask(serviceName, configSettingName);

            checkIfServiceExistsTask.Execute(environment);

            if (bool.Parse(environment.GetConfigSetting(configSettingName)) == true)
            {
                switch (mode)
                {
                case InstallWindowsServiceMode.DoNothingIfExists:
                    return;

                case InstallWindowsServiceMode.FailIfAlreadyInstalled:
                    throw new RunnerFailedException(
                              String.Format(
                                  System.Globalization.CultureInfo.InvariantCulture,
                                  "The Windows service '{0}' already exists.",
                                  serviceName));

                case InstallWindowsServiceMode.ReinstallIfExists:
                    UninstallWindowsServiceTask uninstallWindowsServiceTask = new UninstallWindowsServiceTask(executablePath);
                    uninstallWindowsServiceTask.Execute(environment);

                    // wait for a while to ensure the service is really deleted
                    SleepTask.Execute(environment, serviceUninstallationWaitTime);
                    break;

                default:
                    throw new NotSupportedException();
                }
            }

            IDictionary savedState = new Hashtable();

            string[] commandLine = new string[0];

            using (System.Configuration.Install.AssemblyInstaller assemblyInstaller
                       = new System.Configuration.Install.AssemblyInstaller(executablePath, commandLine))
            {
                try
                {
                    assemblyInstaller.UseNewContext = true;

                    assemblyInstaller.Install(savedState);
                    assemblyInstaller.Commit(savedState);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    // 1073
                    environment.LogMessage(
                        "ex.ErrorCode = {0}",
                        ex.NativeErrorCode);
                    throw;
                }
            }
        }
コード例 #25
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            using (DirectoryEntry rootDirectoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
            {
                DirectoryEntry userEntry = null;

                try
                {
                    // first check if the user already exists
                    try
                    {
                        userEntry = rootDirectoryEntry.Children.Find(userName, "user");

                        // user already exists
                        if (mode == CreateUserAccountMode.DoNothingIfExists)
                        {
                            environment.LogMessage(
                                "User '{0}' already exists, doing nothing.",
                                userName);
                            return;
                        }
                        else if (mode == CreateUserAccountMode.FailIfAlreadyExists)
                        {
                            throw new RunnerFailedException(
                                      String.Format(
                                          System.Globalization.CultureInfo.InvariantCulture,
                                          "User '{0}' already exists.",
                                          userName));
                        }

                        // otherwise we should update the existing user
                    }
                    catch (COMException ex)
                    {
                        if (ex.ErrorCode == -2147022675)
                        {
                            // user does not exist, go on and add it
                            userEntry = rootDirectoryEntry.Children.Add(userName, "user");
                        }
                        else
                        {
                            throw;
                        }
                    }

                    const int ADS_UF_DONT_EXPIRE_PASSWD = 0x00010000;
                    const int ADS_UF_PASSWD_CANT_CHANGE = 0x00000040;

                    userEntry.Invoke("SetPassword", new object[] { password });
                    userEntry.Invoke("Put", new object[] { "Description", userDescription });
                    userEntry.Invoke("Put", new object[] { "userFlags", ADS_UF_DONT_EXPIRE_PASSWD | ADS_UF_PASSWD_CANT_CHANGE });

                    userEntry.CommitChanges();
                }
                finally
                {
                    if (userEntry != null)
                    {
                        userEntry.Dispose();
                    }
                }
            }
        }
コード例 #26
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            string parentName = parentVirtualDirectoryName;

            using (DirectoryEntry parent = new DirectoryEntry(parentName))
            {
                DirectoryEntry virtualDirEntry = null;

                try
                {
                    // first check if the virtual directory already exists
                    try
                    {
                        virtualDirEntry = parent.Children.Find(applicationName, "IIsWebVirtualDir");

                        // virtual directory already exists
                        if (mode == CreateWebApplicationMode.DoNothingIfExists)
                        {
                            environment.LogMessage(
                                "Web application '{0}' already exists, doing nothing.",
                                applicationName);
                            return;
                        }
                        else if (mode == CreateWebApplicationMode.FailIfAlreadyExists)
                        {
                            throw new RunnerFailedException(
                                      String.Format(
                                          System.Globalization.CultureInfo.InvariantCulture,
                                          "Web application '{0}' already exists.",
                                          applicationName));
                        }
                        // otherwise we should update the existing virtual directory
                    }
                    catch (DirectoryNotFoundException)
                    {
                        // virtual directory does not exist, go on and add it
                        virtualDirEntry = parent.Children.Add(applicationName, "IIsWebVirtualDir");
                    }

                    virtualDirEntry.Properties["Path"][0] = localPath;
                    virtualDirEntry.CommitChanges();

                    if (!string.IsNullOrEmpty(applicationPoolName))
                    {
                        virtualDirEntry.Invoke("AppCreate3", new object[] { 2, applicationPoolName, false });
                    }

                    virtualDirEntry.Properties["AppFriendlyName"][0] = appFriendlyName ?? applicationName;

                    int authFlags = 0;
                    if (allowAnonymous)
                    {
                        authFlags |= 1;
                    }
                    if (allowAuthNtlm)
                    {
                        authFlags |= 4;
                    }

                    virtualDirEntry.Properties["AuthFlags"][0] = authFlags;
                    if (anonymousUserName != null)
                    {
                        virtualDirEntry.Properties["AnonymousUserName"][0] = anonymousUserName;
                    }
                    if (anonymousUserPass != null)
                    {
                        virtualDirEntry.Properties["AnonymousUserPass"][0] = anonymousUserPass;
                    }
                    if (defaultDoc != null)
                    {
                        virtualDirEntry.Properties["DefaultDoc"][0] = defaultDoc;
                    }
                    virtualDirEntry.Properties["EnableDefaultDoc"][0] = enableDefaultDoc;

                    virtualDirEntry.Properties["AccessScript"][0]  = true;
                    virtualDirEntry.Properties["AccessExecute"][0] = true;

                    virtualDirEntry.Properties["AspEnableParentPaths"][0] = aspEnableParentPaths;

                    virtualDirEntry.CommitChanges();
                }
                finally
                {
                    if (virtualDirEntry != null)
                    {
                        virtualDirEntry.Dispose();
                    }
                }

                parent.CommitChanges();
            }
        }
コード例 #27
0
        /// <summary>
        /// Method defining the actual work for a task.
        /// </summary>
        /// <param name="environment">The script execution environment.</param>
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            XmlDocument xmldoc = new XmlDocument();

            xmldoc.PreserveWhitespace = true;
            xmldoc.Load(fileName);

            // perform all deletes
            foreach (string xpath in xpathDeletes)
            {
                foreach (XmlNode node in xmldoc.SelectNodes(xpath))
                {
                    string fullNodePath = ConstructXmlNodeFullName(node);

                    environment.LogMessage("Node '{0}' will be removed.", fullNodePath);

                    if (node.NodeType == XmlNodeType.Element)
                    {
                        node.ParentNode.RemoveChild(node);
                    }
                    else if (node.NodeType == XmlNodeType.Attribute)
                    {
                        XmlAttribute attribute = (XmlAttribute)node;
                        attribute.OwnerElement.RemoveAttributeNode(attribute);
                    }
                    else
                    {
                        throw new ArgumentException(
                                  String.Format(
                                      System.Globalization.CultureInfo.InvariantCulture,
                                      "Node '{0}' is of incorrect type '{1}', it should be an element or attribute.",
                                      fullNodePath,
                                      node.NodeType));
                    }
                }
            }

            // perform all updates
            foreach (string xpath in xpathUpdates.Keys)
            {
                foreach (XmlNode node in xmldoc.SelectNodes(xpath))
                {
                    string fullNodePath = ConstructXmlNodeFullName(node);

                    environment.LogMessage(
                        "Node '{0}' will have value '{1}'",
                        fullNodePath,
                        xpathUpdates[xpath]);

                    if (node.NodeType == XmlNodeType.Attribute)
                    {
                        node.Value = xpathUpdates[xpath];
                    }
                    else if (node.NodeType == XmlNodeType.Element)
                    {
                        node.InnerText = xpathUpdates[xpath];
                    }
                    else
                    {
                        throw new ArgumentException(
                                  String.Format(
                                      System.Globalization.CultureInfo.InvariantCulture,
                                      "Node '{0}' is of incorrect type '{1}', it should be an element or attribute.",
                                      fullNodePath,
                                      node.NodeType));
                    }
                }
            }

            // perform all additions
            foreach (UpdateXmlFileTaskAddition addition in xpathAdditions)
            {
                XmlNode rootNode = xmldoc.SelectSingleNode(addition.RootXPath);

                if (rootNode == null)
                {
                    throw new ArgumentException(
                              String.Format(
                                  System.Globalization.CultureInfo.InvariantCulture,
                                  "Path '{0}' does not exist.",
                                  addition.RootXPath));
                }

                if (rootNode.NodeType != XmlNodeType.Element)
                {
                    throw new ArgumentException(
                              String.Format(
                                  System.Globalization.CultureInfo.InvariantCulture,
                                  "Node '{0}' is of incorrect type '{1}', it should be an element.",
                                  addition.RootXPath,
                                  rootNode.NodeType));
                }

                XmlNode childNode = null;
                if (addition.ChildNodeName.StartsWith("@", StringComparison.OrdinalIgnoreCase))
                {
                    childNode       = xmldoc.CreateAttribute(addition.ChildNodeName.Substring(1));
                    childNode.Value = addition.Value;
                    rootNode.Attributes.Append((XmlAttribute)childNode);
                }
                else
                {
                    childNode = xmldoc.CreateElement(addition.ChildNodeName);
                    if (addition.Value != null)
                    {
                        childNode.InnerText = addition.Value;
                    }

                    if (addition.Attributes != null)
                    {
                        XmlElement element = (XmlElement)childNode;

                        foreach (string attribute in addition.Attributes.Keys)
                        {
                            element.SetAttribute(attribute, addition.Attributes[attribute]);
                        }
                    }

                    rootNode.AppendChild(childNode);
                }

                string fullNodePath = ConstructXmlNodeFullName(rootNode);

                environment.LogMessage(
                    "Node '{0}' will have a new child '{1}' with value '{2}'",
                    fullNodePath,
                    childNode.Name,
                    addition.Value);
            }

            xmldoc.Save(fileName);
        }