Blogger

  • This email address is being protected from spambots. You need JavaScript enabled to view it.

    Recent items

Login

Sunday, 24 June 2012 21:35

Custom Http Errors

Written by
Rate this item
(2 votes)

To personalize the ISS Http Errors (for example the http 401.2 error that occurs when an user click con cancel button when credential popup appears), the user must to put the file under the IIS web site folder.

When an developer work with Sharepoint 2010 and have a farm with more front ends, he must copy the error pages in each front end servers under all webapp folders (under IIS inetpub folder).

To make life easier, the developer can implements a WebApp feature that copy the files in all front end servers and modify the web.config files.

The following code descibe the Feature event handler. After the deploy, the administrator must open the Sharepoint Central admin, choices the webapp and active the feture.

The customError folder will deployed under 14\template\layouts folder and when the feature will be activated, the system provide to copy the files and modify the web.config file to add the httpErrors section under configuration/system.webServer section.

 


Show/Hidden csharp code

View source
 
 
 
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;
using System.IO;
using Microsoft.SharePoint.Utilities;
 
namespace ApplyCustomIISErrors
{
    [Guid("00000000-0000-0000-0000-000000000000")]
    public class ApplyCustomIISErrorsEventReceiver : SPFeatureReceiver
    {
 
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPFarm farm = SPFarm.Local;
            string sourceFolder = SPUtility.GetGenericSetupPath("") + "\\TEMPLATE\\LAYOUTS\\customError\\";
 
            if (!string.IsNullOrEmpty(sourceFolder))
            {
                // dynamically find all files in the source folder    
                List<string> filesToDeploy = new List<string>();
                DirectoryInfo folder = new DirectoryInfo(sourceFolder);
                FileInfo[] filesInFolder = folder.GetFiles();
                foreach (FileInfo file in filesInFolder) { filesToDeploy.Add(file.Name); }
 
                // recurse through each web front end    
                foreach (SPServer server in farm.Servers)
                {
                    if (server.Role == SPServerRole.WebFrontEnd || server.Role == SPServerRole.Application)
                    {
                        try
                        {
                            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
                            System.Collections.Generic.Dictionary<SPUrlZone, SPIisSettings> zones = webApp.IisSettings;
                            foreach (System.Collections.Generic.KeyValuePair<SPUrlZone, SPIisSettings> zone in webApp.IisSettings)
                            {
                                SPIisSettings iis = zone.Value;
                                DirectoryInfo dir = iis.Path;
                                string targetPath = dir.ToString() + @"\" + @"customError";
                                string destinationDir = @"\\" + server.Address + @"\" + targetPath.Replace(":", "$");
                                if (!System.IO.Directory.Exists(destinationDir))
                                {
                                    System.IO.Directory.CreateDirectory(destinationDir);
                                }
 
                                // copy support files per web front end
                                foreach (string filename in filesToDeploy)
                                {
                                    string sourceFile = @"\\" + server.Address + @"\" + sourceFolder.Replace(":", "$") + @"\" + filename;
                                    string destinationFile = destinationDir + @"\" + filename;
                                    System.IO.File.Copy(sourceFile, destinationFile, true);
                                }
                            }
                            AddEntryIntoWebConfig(webApp);
 
                        }
                        catch (Exception ex)
                        {
                            
                        }
                    }
                }
            }
        }
 
        #region Web Config Modification
        private const string WebModificationOwnerName = "Automatic Error Pages Deploy Owner";
 
        private void AddEntryIntoWebConfig(SPWebApplication webApp)
        {
            RemoveAllModifications(webApp, WebModificationOwnerName);
 
            string name, value, xpath, xPthRemove;
 
            xpath = "configuration/system.webServer";
            //<HttpErrors errorMode="Custom" existingResponse="Auto" >
            name = "httpErrors[@errorMode='Custom'][@existingResponse='Auto']";
            value = "<httpErrors errorMode='Custom' existingResponse='Auto'></httpErrors>";
            ModifyWebConfig(webApp, xpath, name, value);
            webApp.WebService.Update();
            webApp.WebService.ApplyWebConfigModifications();
 
            xpath = "configuration/system.webServer/httpErrors[2=2]";
            xPthRemove = "configuration/system.webServer/httpErrors[1=1]";
 
            #region HTTP 401
            //<remove statusCode="401" subStatusCode="-1" />
            name = "remove[@statusCode='401'][@subStatusCode='-1']";
            value = "<remove statusCode='401' subStatusCode='-1' />";
            ModifyWebConfig(webApp, xPthRemove, name, value);
 
            //<error statusCode="401" prefixLanguageFilePath="" path="customError\401.html" responseMode="File" />
            name = @"error[@statusCode='401'][@prefixLanguageFilePath=''][@path='customError\401.html'][@responseMode='File']";
            value = @"<error statusCode='401' prefixLanguageFilePath='' path='customError\401.html' responseMode='File' />";
            ModifyWebConfig(webApp, xpath, name, value);
            #endregion
 
            #region HTTP 403
            //<remove statusCode="403" subStatusCode="-1" />
            name = "remove[@statusCode='403'][@subStatusCode='-1']";
            value = "<remove statusCode='403' subStatusCode='-1' />";
            ModifyWebConfig(webApp, xPthRemove, name, value);
 
            //<error statusCode="403" prefixLanguageFilePath="" path="customError\403.html" responseMode="File" />
            name = @"error[@statusCode='403'][@prefixLanguageFilePath=''][@path='customError\403.html'][@responseMode='File']";
            value = @"<error statusCode='403' prefixLanguageFilePath='' path='customError\403.html' responseMode='File' />";
            ModifyWebConfig(webApp, xpath, name, value);
            #endregion
 
            #region other errors
            
            #endregion
 
            try
            {
                webApp.WebService.ApplyWebConfigModifications();
            }
            catch (Exception ex)
            {
                RemoveAllModifications(webApp, WebModificationOwnerName);
                webApp.Update();
                webApp.WebService.ApplyWebConfigModifications();
            }
        }
 
        private void RemoveAllModifications(SPWebApplication webApp, string owner)
        {
            List<SPWebConfigModification> modificationsToRemove = new List<SPWebConfigModification>();
            foreach (SPWebConfigModification modification in webApp.WebConfigModifications)
                if (modification.Owner == owner)
                    modificationsToRemove.Add(modification);
 
            foreach (SPWebConfigModification modification in modificationsToRemove)
                webApp.WebConfigModifications.Remove(modification);
 
            webApp.Update();
        }
 
        private void ModifyWebConfig(SPWebApplication webApp, string path, string nameModif, string valueModif)
        {
            SPWebConfigModification modification = new SPWebConfigModification(nameModif, path);
            modification.Value = valueModif;
            modification.Sequence = 0;
            modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            modification.Owner = WebModificationOwnerName;
 
            webApp.WebConfigModifications.Add(modification);
            webApp.Update();
        }
       
        #endregion
 
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPFarm farm = SPFarm.Local;
            string sourceFolder = SPUtility.GetGenericSetupPath("") + "\\TEMPLATE\\LAYOUTS\\customError\\";
            
            // dynamically find all files in the source folder    
            if (!string.IsNullOrEmpty(sourceFolder))
            {
                List<string> filesToDeploy = new List<string>();
                DirectoryInfo folder = new DirectoryInfo(sourceFolder);
                FileInfo[] filesInFolder = folder.GetFiles();
                foreach (FileInfo file in filesInFolder) { filesToDeploy.Add(file.Name); }
 
                // recurse through each web front end    
                foreach (SPServer server in farm.Servers)
                {
                    if (server.Role == SPServerRole.WebFrontEnd || server.Role == SPServerRole.Application)
                    {
                        try
                        {
                            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
                            foreach (System.Collections.Generic.KeyValuePair<SPUrlZone, SPIisSettings> zone in webApp.IisSettings)
                            {
                                SPIisSettings iis = zone.Value;
                                DirectoryInfo dir = iis.Path;
                                string targetPath = dir.ToString() + @"\" + @"customError";
                                if (System.IO.Directory.Exists(targetPath))
                                {
                                    foreach (string filename in filesToDeploy)
                                    {
                                        string delFile = @"\\" + server.Address + @"\" + targetPath.Replace(":", "$") + @"\" + filename;
                                        System.IO.File.Delete(delFile);
                                    }
                                    string delDir = @"\\" + server.Address + @"\" + targetPath.Replace(":", "$");
                                    System.IO.Directory.Delete(delDir);
                                }
                            }
 
                            RemoveAllModifications(webApp,WebModificationOwnerName);
                            webApp.WebService.ApplyWebConfigModifications();
                        }
                        catch (Exception ex)
                        {
                        
                        }
                    }
                }
            }
        }
    }
}
 
 
 
 

Read 45505 times Last modified on Tuesday, 12 January 2016 10:45

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.