Thursday, December 27, 2012

Switch web application over IIS to redirect to other application in the same server

Following code switches web application over IIS to redirect to other application in the same server. Inputs of the code: "serverName" - server name of the application which hosts applications over IIS, "path" - physical path of the application folder, "newSiteFolder" - folder name of the application we want redirect to
     public static bool ChangeApplicationFolder(string serverName, string path, string newSiteFolder)
        {
            try
            {
                string[] tokens = path.Split('\\');
                if (tokens.Length < 4)
                {
                    return false;
                }

                string siteName = tokens[tokens.Length - 1];
                lock (_lock)
                {
                    ServerManager server;
                    Site site;

                    GetSiteAndServer(serverName, siteName, out server, out site);
                    if (site == null)
                    {
                        return false;
                    }
                    tokens[tokens.Length - 1] = newSiteFolder;
                    string maintenancePath = GetPhysicalPath(tokens);
                    site.Applications["/"].VirtualDirectories["/"].PhysicalPath = maintenancePath;
                    server.CommitChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                
                return false;
            }
        }
  
  
  private static void GetSiteAndServer(string serverName, string siteName, out ServerManager server, out Site site)
        {
            server = (string.IsNullOrEmpty(serverName) || serverName == "127.0.0.1") ? new ServerManager() : ServerManager.OpenRemote(serverName);
            site = null;
            if (server != null)
            {
                site = server.Sites.FirstOrDefault(s => s.Name.ToLower() == siteName.ToLower());
            }
        }
  
  private static string GetPhysicalPath(string[] tokens)
        {
            List newTokens = new List();
            for (int i = 3; i < tokens.Length; i++)
            {
                newTokens.Add(tokens[i]);
            }

            string originalPath = newTokens.Aggregate((a, b) => a + "\\" + b);
            originalPath = originalPath.Replace('$', ':');
            return originalPath;
        }

1 comment: