/// <summary> /// Removes the application - reachable at the specified port - and its application pools from IIS. /// Note: Stops the application pools and the application if necessary /// </summary> /// <param name="port">The port.</param> private static void Delete(int port) { mut.WaitOne(); try { using (ServerManager serverMgr = new ServerManager()) { Site currentSite = null; foreach (Site site in serverMgr.Sites) { if (site.Bindings[0].EndPoint.Port == port) { currentSite = site; break; } } int retryCount = 20; while (retryCount > 0) { try { serverMgr.Sites[currentSite.Name].Stop(); break; } catch (System.Runtime.InteropServices.COMException) { // todo log exception } retryCount--; } int time = 0; while (serverMgr.Sites[currentSite.Name].State != ObjectState.Stopped && time < 300) { Thread.Sleep(100); time++; } if (time == 300) { KillApplicationProcesses(currentSite.Applications["/"].ApplicationPoolName); } serverMgr.Sites.Remove(currentSite); serverMgr.CommitChanges(); FirewallTools.ClosePort(port); ApplicationPool applicationPool = serverMgr.ApplicationPools[currentSite.Applications["/"].ApplicationPoolName]; serverMgr.ApplicationPools[applicationPool.Name].Stop(); time = 0; while (serverMgr.ApplicationPools[applicationPool.Name].State != ObjectState.Stopped && time < 300) { Thread.Sleep(100); time++; } if (serverMgr.ApplicationPools[applicationPool.Name].State != ObjectState.Stopped && time == 300) { KillApplicationProcesses(applicationPool.Name); } serverMgr.ApplicationPools.Remove(applicationPool); serverMgr.CommitChanges(); string username = null; username = applicationPool.ProcessModel.UserName; if (username != null) { string path = currentSite.Applications["/"].VirtualDirectories["/"].PhysicalPath; if (Directory.Exists(path)) { DirectoryInfo deploymentDir = new DirectoryInfo(path); DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl(); deploymentDirSecurity.RemoveAccessRuleAll(new FileSystemAccessRule(username, FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify, AccessControlType.Allow)); deploymentDir.SetAccessControl(deploymentDirSecurity); } } } } finally { mut.ReleaseMutex(); } }