Ejemplo n.º 1
0
 internal static void CreateHttpRuntime(string appVPath) {
     var runtime = new HttpRuntime();
     var appDomainAppVPathField = typeof(HttpRuntime).GetField("_appDomainAppVPath", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
     appDomainAppVPathField.SetValue(runtime, CreateVirtualPath(appVPath));
     GetTheRuntime().SetValue(null, runtime);
     var appDomainIdField = typeof(HttpRuntime).GetField("_appDomainId", BindingFlags.NonPublic | BindingFlags.Instance);
     appDomainIdField.SetValue(runtime, "test");
 }
Ejemplo n.º 2
0
 private static void EnsureHttpRuntime()
 {
     if (httpRuntime == null)
     {
         lock (initSync)
         {
             if (httpRuntime == null) httpRuntime = new HttpRuntime();
         }
     }
 } 
Ejemplo n.º 3
0
 private void EnsureHttpRuntime()
 {
     if (null == httpRuntime)
     {
         try
         {
             Monitor.Enter(typeof(Yammer.Assets));
             if (null == httpRuntime)
                 httpRuntime = new HttpRuntime();
         }
         finally
         {
             Monitor.Exit(typeof(Yammer.Assets));
         }
     }
 }
Ejemplo n.º 4
0
		private static void EnsureHttpRuntime()
		{
			try
			{
				Monitor.Enter(typeof(CacheIt));
				if (null == _httpRuntime)
				{
					_httpRuntime = new HttpRuntime();

				}
			}
			finally
			{
				Monitor.Exit(typeof(CacheIt));
			}

		}
Ejemplo n.º 5
0
        //private readonly object _fileChangesManager;
        //private readonly FieldInfo _callbackFieldInfo;
        //private readonly FieldInfo _isFCNDisabledFieldInfo;
        //private readonly object _savedCallbackValue;


        /// <exclude />
        public ShutdownGuard()
        {
            if (!HostingEnvironment.IsHosted)
            {
                return;
            }

            const BindingFlags getStaticFieldValue = BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField;
            _runtime = (HttpRuntime)typeof(HttpRuntime).InvokeMember("_theRuntime", getStaticFieldValue, null, null, null);
            _hostingEnvironment = (HostingEnvironment)typeof(HostingEnvironment).InvokeMember("_theHostingEnvironment", getStaticFieldValue, null, null, null);


            const BindingFlags privateField = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField;
            _shutdownWebEventRaised_FieldInfo = typeof(HttpRuntime).GetField("_shutdownWebEventRaised", privateField);

            // In .NET 3.5 the field is called "_shutdownInitated"
            //    .NET 4.0 the field is called "_shutdownInitiated"
            _shutdownInitiated_FieldInfo = typeof(HostingEnvironment).GetField("_shutdownInitiated", privateField)
                                        ?? typeof(HostingEnvironment).GetField("_shutdownInitated",  privateField);

            // Simulating situation, when all events to unload current AppDomain were already raised.
            _shutdownWebEventRaised_FieldInfo.SetValue(_runtime, true);
            _shutdownInitiated_FieldInfo.SetValue(_hostingEnvironment, true);



            //_fileChangesManager = runtime.GetType().GetField("_fcm", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField).GetValue(runtime);

            //_callbackFieldInfo = _fileChangesManager.GetType().GetField("_callbackRenameOrCriticaldirChange",
            //                                                                    BindingFlags.NonPublic |
            //                                                                    BindingFlags.Instance |
            //                                                                    BindingFlags.GetField);

            //_isFCNDisabledFieldInfo = _fileChangesManager.GetType().GetField("_FCNMode",
            //                                                                    BindingFlags.NonPublic |
            //                                                                    BindingFlags.Instance |
            //                                                                    BindingFlags.GetField);

            //_savedCallbackValue = _callbackFieldInfo.GetValue(_fileChangesManager);
            //_callbackFieldInfo.SetValue(_fileChangesManager, null);

            //// Turning off file change notifications. http://support.microsoft.com/kb/911272
            //_isFCNDisabledFieldInfo.SetValue(_fileChangesManager, (Int32)1);


        }
Ejemplo n.º 6
0
        private static FileInfo GetFileInfo(string virtualPathWithPathInfo, string physicalPath, HttpResponse response)
        {
            // Check whether the file exists
            if (!FileUtil.FileExists(physicalPath))
            {
                throw new HttpException(HttpStatus.NotFound,
                                        SR.GetString(SR.File_does_not_exist));
            }
            // To prevent the trailing dot problem, error out all file names with trailing dot.
            if (physicalPath[physicalPath.Length - 1] == '.')
            {
                throw new HttpException(HttpStatus.NotFound,
                                        SR.GetString(SR.File_does_not_exist));
            }

            FileInfo fileInfo;

            try {
                fileInfo = new FileInfo(physicalPath);
            }
            catch (IOException ioEx) {
                if (!HttpRuntime.HasFilePermission(physicalPath))
                {
                    throw new HttpException(HttpStatus.NotFound,
                                            SR.GetString(SR.Error_trying_to_enumerate_files));
                }
                else
                {
                    throw new HttpException(HttpStatus.NotFound,
                                            SR.GetString(SR.Error_trying_to_enumerate_files),
                                            ioEx);
                }
            }
            catch (SecurityException secEx) {
                if (!HttpRuntime.HasFilePermission(physicalPath))
                {
                    throw new HttpException(HttpStatus.Unauthorized,
                                            SR.GetString(SR.File_enumerator_access_denied));
                }
                else
                {
                    throw new HttpException(HttpStatus.Unauthorized,
                                            SR.GetString(SR.File_enumerator_access_denied),
                                            secEx);
                }
            }

            // To be consistent with IIS, we won't serve out hidden files
            if ((((int)fileInfo.Attributes) & ((int)FileAttributes.Hidden)) != 0)
            {
                throw new HttpException(HttpStatus.NotFound,
                                        SR.GetString(SR.File_is_hidden));
            }

            // If the file is a directory, then it must not have a slash in
            // end of it (if it does have a slash suffix, then the config file
            // mappings are missing and we will just return 403.  Otherwise,
            // we will redirect the client to the URL with this slash.
            if ((((int)fileInfo.Attributes) & ((int)FileAttributes.Directory)) != 0)
            {
                if (StringUtil.StringEndsWith(virtualPathWithPathInfo, '/'))
                {
                    // Just return 403
                    throw new HttpException(HttpStatus.Forbidden,
                                            SR.GetString(SR.Missing_star_mapping));
                }
                else
                {
                    // Redirect to a slash suffixed URL which will be
                    // handled by the */ handler mapper
                    response.Redirect(virtualPathWithPathInfo + "/");
                }
            }

            return(fileInfo);
        }
Ejemplo n.º 7
0
        /*
         * Return the text of the error line in the source file, with a few
         * lines around it.  It is returned in HTML format.
         */
        internal static string GetSourceFileLines(string fileName, Encoding encoding, string sourceCode, int lineNumber)
        {
            // Don't show any source file if the user doesn't have access to it (ASURT 122430)
            if (fileName != null && !HttpRuntime.HasFilePermission(fileName))
            {
                return(HttpRuntime.FormatResourceString(SR.WithFile_No_Relevant_Line));
            }

            // REVIEW: write directly to the main builder
            StringBuilder sb = new StringBuilder();

            if (lineNumber <= 0)
            {
                return(HttpRuntime.FormatResourceString(SR.WithFile_No_Relevant_Line));
            }

            TextReader reader = null;

            fileName = ResolveHttpFileName(fileName);

            try {
                // Open the source file
                reader = new StreamReader(fileName, encoding, true, 4096);
            }
            catch (Exception) {
                // Can't open the file?  Use the dynamically generated content...
                reader = new StringReader(sourceCode);
            }

            try {
                bool fFoundLine = false;

                for (int i = 1; ; i++)
                {
                    // Get the current line from the source file
                    string sourceLine = reader.ReadLine();
                    if (sourceLine == null)
                    {
                        break;
                    }

                    // If it's the error line, make it red
                    if (i == lineNumber)
                    {
                        sb.Append("<font color=red>");
                    }

                    // Is it in the range we want to display
                    if (i >= lineNumber - errorRange && i <= lineNumber + errorRange)
                    {
                        fFoundLine = true;
                        String linestr = i.ToString("G");

                        sb.Append(HttpRuntime.FormatResourceString(SR.WithFile_Line_Num, linestr));
                        if (linestr.Length < 3)
                        {
                            sb.Append(' ', 3 - linestr.Length);
                        }
                        sb.Append(HttpUtility.HtmlEncode(sourceLine));

                        if (i != lineNumber + errorRange)
                        {
                            sb.Append("\r\n");
                        }
                    }

                    if (i == lineNumber)
                    {
                        sb.Append("</font>");
                    }

                    if (i > lineNumber + errorRange)
                    {
                        break;
                    }
                }

                if (!fFoundLine)
                {
                    return(HttpRuntime.FormatResourceString(SR.WithFile_No_Relevant_Line));
                }
            }
            finally {
                // Make sure we always close the reader
                reader.Close();
            }

            return(sb.ToString());
        }
Ejemplo n.º 8
0
        /*  InitRequest
         *  Initialize the given dataset with basic
         *  request information
         */
        private void InitRequest()
        {
            // Master request is assumed to be initialized first
            System.Web.Util.Debug.Assert(_masterRequest != null);

            DataSet requestData = _masterRequest.Clone();

            // request info
            DataRow row = NewRow(requestData, SR.Trace_Request);

            row[SR.Trace_Time_of_Request] = _context.Timestamp.ToString("G");

            string url = _context.Request.RawUrl;
            int    loc = url.IndexOf("?", StringComparison.Ordinal);

            if (loc != -1)
            {
                url = url.Substring(0, loc);
            }
            row[SR.Trace_Url] = url;

            row[SR.Trace_Request_Type] = _context.Request.HttpMethod;
            try {
                row[SR.Trace_Request_Encoding] = _context.Request.ContentEncoding.EncodingName;
            }
            catch {
                // if we get an exception getting the ContentEncoding, most likely
                // there's an error in the config file.  Just ignore it so we can finish InitRequest.
            }

            if (TraceMode == TraceMode.SortByCategory)
            {
                requestData.Tables[SR.Trace_Trace_Information].DefaultView.Sort = SR.Trace_Category;
            }
            AddRow(requestData, SR.Trace_Request, row);

            // header info
            try {
                // Bug 867196: Use Request.Unvalidated to ensure request validation will not
                // be triggered when the entries of the collection are accessed.
                AddCollectionToRequestData(requestData, SR.Trace_Headers_Collection, _context.Request.Unvalidated.Headers);
            }
            catch {
                // ---- exceptions when we fail to get the unvalidated collection
            }

            // response header info
            ArrayList headers = _context.Response.GenerateResponseHeaders(false);
            int       n       = (headers != null) ? headers.Count : 0;

            for (int i = 0; i < n; i++)
            {
                HttpResponseHeader h = (HttpResponseHeader)headers[i];
                row = NewRow(requestData, SR.Trace_Response_Headers_Collection);
                row[SR.Trace_Name]  = h.Name;
                row[SR.Trace_Value] = h.Value;
                AddRow(requestData, SR.Trace_Response_Headers_Collection, row);
            }

            //form info
            try {
                AddCollectionToRequestData(requestData, SR.Trace_Form_Collection, _context.Request.Unvalidated.Form);
            }
            catch {
                // ---- exceptions when we fail to get the unvalidated collection
            }

            //QueryString info
            try {
                AddCollectionToRequestData(requestData, SR.Trace_Querystring_Collection, _context.Request.Unvalidated.QueryString);
            }
            catch {
                // ---- exceptions when we fail to get the unvalidated collection
            }

            //Server Variable info
            if (HttpRuntime.HasAppPathDiscoveryPermission())
            {
                AddCollectionToRequestData(requestData, SR.Trace_Server_Variables, _context.Request.ServerVariables);
            }

            _requestData = requestData;

            if (HttpRuntime.UseIntegratedPipeline)
            {
                // Dev10 914119: When trace is enabled, the request entity is read and no longer
                // available to IIS.  In integrated mode, we have an API that allows us to reinsert
                // the entity.  Although it is expensive, performance is not a concern when
                // trace is enalbed, so we will reinsert just in case a native handler needs
                // to access the entity.  I decided not to check the current handler, since
                // that can be changed if someone sets the IIS script map.
                _context.Request.InsertEntityBody();
            }
        }
Ejemplo n.º 9
0
 private void OnAppFileChange(Object sender, FileChangeEvent e)
 {
     // shutdown the app domain if app file changed
     Debug.Trace("AppDomainFactory", "Shutting down appdomain because of application file change");
     HttpRuntime.ShutdownAppDomain("Change in GLOBAL.ASAX");
 }
        internal static HttpException CreateFileMonitoringException(int hr, string path)
        {
            string str;
            bool   flag = false;

            switch (hr)
            {
            case -2147024894:
            case -2147024893:
                str = "Directory_does_not_exist_for_monitoring";
                break;

            case -2147024891:
                str  = "Access_denied_for_monitoring";
                flag = true;
                break;

            case -2147024840:
                str  = "NetBios_command_limit_reached";
                flag = true;
                break;

            case -2147024809:
                str = "Invalid_file_name_for_monitoring";
                break;

            default:
                str = "Failed_to_start_monitoring";
                break;
            }
            if (flag)
            {
                System.Web.UnsafeNativeMethods.RaiseFileMonitoringEventlogEvent(System.Web.SR.GetString(str, new object[] { HttpRuntime.GetSafePath(path) }) + "\n\r" + System.Web.SR.GetString("App_Virtual_Path", new object[] { HttpRuntime.AppDomainAppVirtualPath }), path, HttpRuntime.AppDomainAppVirtualPath, hr);
            }
            return(new HttpException(System.Web.SR.GetString(str, new object[] { HttpRuntime.GetSafePath(path) }), hr));
        }
Ejemplo n.º 11
0
        static void OnFileChanged(object sender, FileSystemEventArgs args)
        {
            if (HttpRuntime.DomainUnloading)
            {
                return;
            }
            string name     = args.Name;
            bool   isConfig = false;

            if (StrUtils.EndsWith(name, "onfig", true))
            {
                if (String.Compare(Path.GetFileName(name), "web.config", true, Helpers.InvariantCulture) != 0)
                {
                    return;
                }
                isConfig = true;
            }
            else if (StrUtils.EndsWith(name, "lobal.asax", true) && String.Compare(name, "global.asax", true, Helpers.InvariantCulture) != 0)
            {
                return;
            }

            Console.WriteLine("Change: " + name);

            // {Inotify,FAM}Watcher will notify about events for a directory regardless
            // of the filter pattern. This might be a bug in the watchers code, but
            // since I couldn't find any rationale for the code in there I'd opted for
            // not removing it and instead working around the issue here. Fix for bug
            // #495011
            FileSystemWatcher watcher = sender as FileSystemWatcher;

            if (watcher != null && String.Compare(watcher.Filter, "?eb.?onfig", true, Helpers.InvariantCulture) == 0 && Directory.Exists(name))
            {
                return;
            }

            // We re-enable suppression here since WebConfigurationManager will disable
            // it after save is done. WebConfigurationManager is called twice by
            // Configuration - just after opening the target file and just after closing
            // it. For that reason we will receive two change notifications and if we
            // disabled suppression here, it would reload the application on the second
            // change notification.
            if (isConfig && WebConfigurationManager.SuppressAppReload(true))
            {
                return;
            }

            lock (watchers_lock) {
                if (app_shutdown)
                {
                    return;
                }
                app_shutdown = true;

                // Disable event raising to avoid concurrent restarts
                DisableWatchers();

                // Restart application
                HttpRuntime.UnloadAppDomain();
            }
        }
 public override void Remove(String name)
 {
     throw new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_modify_server_vars));
 }
Ejemplo n.º 13
0
        /// <include file='doc\ProcessModelInfo.uex' path='docs/doc[@for="ProcessModelInfo.GetHistory"]/*' />
        static public ProcessInfo[]  GetHistory(int numRecords)
        {
            InternalSecurityPermissions.AspNetHostingPermissionLevelHigh.Demand();

            HttpContext context = HttpContext.Current;

            if (context == null || context.WorkerRequest == null ||
                !(context.WorkerRequest is System.Web.Hosting.ISAPIWorkerRequestOutOfProc))
            {
                throw new HttpException(HttpRuntime.FormatResourceString(SR.Process_information_not_available));
            }

            if (numRecords < 1)
            {
                return(null);
            }

            int []  dwPID  = new int [numRecords];
            int []  dwExed = new int [numRecords];
            int []  dwExei = new int [numRecords];
            int []  dwPend = new int [numRecords];
            int []  dwReas = new int [numRecords];
            long [] tmCrea = new long [numRecords];
            long [] tmDeat = new long [numRecords];
            int []  mem    = new int [numRecords];

            int iRows = UnsafeNativeMethods.PMGetHistoryTable(numRecords, dwPID, dwExed, dwPend, dwExei, dwReas, mem, tmCrea, tmDeat);

            if (iRows < 0)
            {
                throw new HttpException(HttpRuntime.FormatResourceString(SR.Process_information_not_available));
            }

            ProcessInfo[] ret = new ProcessInfo[iRows];
            for (int iter = 0; iter < iRows; iter++)
            {
                DateTime startTime = DateTime.FromFileTime(tmCrea[iter]);
                TimeSpan age       = DateTime.Now.Subtract(startTime);

                ProcessStatus         status = ProcessStatus.Alive;
                ProcessShutdownReason rea    = ProcessShutdownReason.None;

                if (dwReas[iter] != 0)
                {
                    if (tmDeat[iter] > 0)
                    {
                        age = DateTime.FromFileTime(tmDeat[iter]).Subtract(startTime);
                    }

                    if ((dwReas[iter] & 0x0004) != 0)
                    {
                        status = ProcessStatus.Terminated;
                    }
                    else if ((dwReas[iter] & 0x0002) != 0)
                    {
                        status = ProcessStatus.ShutDown;
                    }
                    else
                    {
                        status = ProcessStatus.ShuttingDown;
                    }

                    if ((0x0040 & dwReas[iter]) != 0)
                    {
                        rea = ProcessShutdownReason.IdleTimeout;
                    }
                    else if ((0x0080 & dwReas[iter]) != 0)
                    {
                        rea = ProcessShutdownReason.RequestsLimit;
                    }
                    else if ((0x0100 & dwReas[iter]) != 0)
                    {
                        rea = ProcessShutdownReason.RequestQueueLimit;
                    }
                    else if ((0x0020 & dwReas[iter]) != 0)
                    {
                        rea = ProcessShutdownReason.Timeout;
                    }
                    else if ((0x0200 & dwReas[iter]) != 0)
                    {
                        rea = ProcessShutdownReason.MemoryLimitExceeded;
                    }
                    else if ((0x0400 & dwReas[iter]) != 0)
                    {
                        rea = ProcessShutdownReason.PingFailed;
                    }
                    else if ((0x0800 & dwReas[iter]) != 0)
                    {
                        rea = ProcessShutdownReason.DeadlockSuspected;
                    }
                    else
                    {
                        rea = ProcessShutdownReason.Unexpected;
                    }
                }

                ret[iter] = new ProcessInfo(startTime, age, dwPID[iter], dwExed[iter], status, rea, mem[iter]);
            }

            return(ret);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Ensures the HTTP runtime.
 /// </summary>
 private static void EnsureHttpRuntime()
 {
     if (null == _httpRuntime)
       {
     try
     {
       Monitor.Enter(typeof (BasePage));
       if (null == _httpRuntime)
       {
     // Create an Http Content to give us access to the cache.
     _httpRuntime = new HttpRuntime();
       }
     }
     finally
     {
       Monitor.Exit(typeof (BasePage));
     }
       }
 }
Ejemplo n.º 15
0
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        // Private stuff

        //////////////////////////////////////////////////////////////////////
        // Create a manifest from a manifest file
        static internal MyWebManifest CreateFromFile(
            String strFile,
            String strUrl,
            bool installed,
            bool donotfail)
        {
            String []         strProperties = null;
            ConfigXmlDocument xmlDoc        = null;
            ConfigXmlCursor   cursor        = null;
            int           iter        = 0;
            int           iRet        = 0;
            StringBuilder strBuf      = new StringBuilder(1024);
            bool          fFound      = false;
            ArrayList     customUrls  = new ArrayList();
            ArrayList     customUrlDs = new ArrayList();
            String        strRandom   = System.Web.SessionState.SessionId.Create();

            ////////////////////////////////////////////////////////////
            // Step 1: Parse the file and get the other properties
            try {
                xmlDoc = new ConfigXmlDocument();
                xmlDoc.Load(strFile);
                cursor = xmlDoc.GetCursor();
                cursor.MoveToFirstChild();
            }
            catch (Exception e) {
                if (!donotfail)
                {
                    throw e;
                }
                cursor = null;
            }

            if (cursor != null)
            {
                do
                {
                    if (cursor.Type == ConfigXmlElement.Element && cursor.Name.ToLower(CultureInfo.InvariantCulture).Equals("softpkg"))
                    {
                        fFound = true;
                        break;
                    }
                }while (cursor.MoveNext());
            }

            if (!fFound && !donotfail)
            {
                return(null);
            }

            ////////////////////////////////////////////////////////////
            // Step 2: Get the non-manifest file properties
            strProperties = new String[NUM_PROPERTIES];
            for (iter = 0; iter < NUM_PROPERTIES; iter++)
            {
                strProperties[iter] = String.Empty;
            }

            strProperties[_ApplicationUrl] = strUrl.Replace('\\', '/');
            strProperties[_ManifestFile]   = strFile;

            if (!installed)
            {
                iRet = NativeMethods.MyWebGetInstallLocationForUrl(MyWeb.GetDefaultInstallLocation(),
                                                                   strUrl, strRandom, strBuf, 1024);

                if (iRet < 0)
                {
                    iRet   = -iRet + 100;
                    strBuf = new StringBuilder(iRet);
                    iRet   = NativeMethods.MyWebGetInstallLocationForUrl(MyWeb.GetDefaultInstallLocation(),
                                                                         strUrl, strRandom, strBuf, iRet);
                }
                if (iRet <= 0)
                {
                    throw new HttpException(HttpRuntime.FormatResourceString(SR.Unable_to_get_app_location));
                }

                strProperties[_InstalledLocation] = strBuf.ToString();
            }
            else
            {
                strProperties[_InstalledLocation] = strFile.Substring(0, strFile.LastIndexOf('\\'));
            }


            if (cursor == null && donotfail)
            {
                return(new MyWebManifest(strProperties, installed, new String[0], new String[0]));
            }

            strProperties[_Name]    = cursor.AttributeText("name");
            strProperties[_Version] = cursor.AttributeText("version");
            cursor.MoveToFirstChild();
            do
            {
                if (cursor.Type == ConfigXmlElement.Element)
                {
                    String strName = cursor.Name.ToLower(CultureInfo.InvariantCulture);

                    if (strName.Equals("implementation"))
                    {
                        strProperties[_CabFile] = GetCabFileNameFromCursor(cursor);
                    }
                    else if (strName.Equals("license"))
                    {
                        strProperties[_License] = cursor.AttributeText("href");
                    }
                    else if (strName.Equals("customurl"))
                    {
                        String strC = cursor.AttributeText("href");
                        String strD = cursor.AttributeText("description");
                        customUrls.Add(strC);
                        customUrlDs.Add(strD);
                    }
                    else
                    {
                        for (iter = 0; iter < _OtherProperties.Length; iter++)
                        {
                            if (strName.Equals(_OtherProperties[iter]))
                            {
                                strProperties[OTHER_PROP_START + iter] = GetCursorText(cursor);
                                break;
                            }
                        }
                    }
                }
            }while (cursor.MoveNext());

            return(new MyWebManifest(strProperties, installed, customUrls.ToArray(), customUrlDs.ToArray()));
        }
Ejemplo n.º 16
0
 protected void Page_Load(object sender, EventArgs e)
 {
     HttpRuntime r = new HttpRuntime();
 }
Ejemplo n.º 17
0
 static HttpRuntime()
 {
   HttpRuntime.AddAppDomainTraceMessage("*HttpRuntime::cctor");
   HttpRuntime.StaticInit();
   HttpRuntime._theRuntime = new HttpRuntime();
   HttpRuntime._theRuntime.Init();
   HttpRuntime.AddAppDomainTraceMessage("HttpRuntime::cctor*");
 }
 internal void StopMonitoringPath(string alias, object target)
 {
     if (!this.IsFCNDisabled)
     {
         DirectoryMonitor directoryMonitor = null;
         string           fileNameLong     = null;
         if (alias == null)
         {
             throw new HttpException(System.Web.SR.GetString("Invalid_file_name_for_monitoring", new object[] { string.Empty }));
         }
         using (new ApplicationImpersonationContext())
         {
             this._lockDispose.AcquireReaderLock();
             try
             {
                 if (!this._disposed)
                 {
                     FileMonitor monitor = (FileMonitor)this._aliases[alias];
                     if (monitor != null)
                     {
                         directoryMonitor = monitor.DirectoryMonitor;
                         fileNameLong     = monitor.FileNameLong;
                     }
                     else
                     {
                         if ((alias.Length == 0) || !UrlPath.IsAbsolutePhysicalPath(alias))
                         {
                             throw new HttpException(System.Web.SR.GetString("Invalid_file_name_for_monitoring", new object[] { HttpRuntime.GetSafePath(alias) }));
                         }
                         string fullPath = GetFullPath(alias);
                         directoryMonitor = this.FindDirectoryMonitor(fullPath, false, false);
                         if (directoryMonitor == null)
                         {
                             string directoryOrRootName = UrlPath.GetDirectoryOrRootName(fullPath);
                             fileNameLong = Path.GetFileName(fullPath);
                             if (!string.IsNullOrEmpty(fileNameLong))
                             {
                                 directoryMonitor = this.FindDirectoryMonitor(directoryOrRootName, false, false);
                             }
                         }
                     }
                     if (directoryMonitor != null)
                     {
                         directoryMonitor.StopMonitoringFile(fileNameLong, target);
                     }
                 }
             }
             finally
             {
                 this._lockDispose.ReleaseReaderLock();
             }
         }
     }
 }
        internal DateTime StartMonitoringPath(string alias, FileChangeEventHandler callback, out FileAttributesData fad)
        {
            FileMonitor      monitor  = null;
            DirectoryMonitor monitor2 = null;
            string           fullPath;
            string           file = null;
            bool             flag = false;

            fad = null;
            if (alias == null)
            {
                throw new HttpException(System.Web.SR.GetString("Invalid_file_name_for_monitoring", new object[] { string.Empty }));
            }
            if (this.IsFCNDisabled)
            {
                fullPath = GetFullPath(alias);
                FindFileData data = null;
                if (FindFileData.FindFile(fullPath, out data) == 0)
                {
                    fad = data.FileAttributesData;
                    return(data.FileAttributesData.UtcLastWriteTime);
                }
                return(DateTime.MinValue);
            }
            using (new ApplicationImpersonationContext())
            {
                this._lockDispose.AcquireReaderLock();
                try
                {
                    if (this._disposed)
                    {
                        return(DateTime.MinValue);
                    }
                    monitor = (FileMonitor)this._aliases[alias];
                    if (monitor != null)
                    {
                        file    = monitor.FileNameLong;
                        monitor = monitor.DirectoryMonitor.StartMonitoringFileWithAssert(file, callback, alias);
                    }
                    else
                    {
                        flag = true;
                        if ((alias.Length == 0) || !UrlPath.IsAbsolutePhysicalPath(alias))
                        {
                            throw new HttpException(System.Web.SR.GetString("Invalid_file_name_for_monitoring", new object[] { HttpRuntime.GetSafePath(alias) }));
                        }
                        fullPath = GetFullPath(alias);
                        if (this.IsBeneathAppPathInternal(fullPath))
                        {
                            monitor2 = this._dirMonAppPathInternal;
                            file     = fullPath.Substring(this._appPathInternal.Length + 1);
                            monitor  = monitor2.StartMonitoringFileWithAssert(file, callback, alias);
                        }
                        else
                        {
                            monitor2 = this.FindDirectoryMonitor(fullPath, false, false);
                            if (monitor2 != null)
                            {
                                monitor = monitor2.StartMonitoringFileWithAssert(null, callback, alias);
                            }
                            else
                            {
                                string directoryOrRootName = UrlPath.GetDirectoryOrRootName(fullPath);
                                file = Path.GetFileName(fullPath);
                                if (!string.IsNullOrEmpty(file))
                                {
                                    monitor2 = this.FindDirectoryMonitor(directoryOrRootName, false, false);
                                    if (monitor2 != null)
                                    {
                                        try
                                        {
                                            monitor = monitor2.StartMonitoringFileWithAssert(file, callback, alias);
                                        }
                                        catch
                                        {
                                        }
                                        if (monitor != null)
                                        {
                                            goto Label_01C7;
                                        }
                                    }
                                }
                                monitor2 = this.FindDirectoryMonitor(fullPath, true, false);
                                if (monitor2 != null)
                                {
                                    file = null;
                                }
                                else
                                {
                                    if (string.IsNullOrEmpty(file))
                                    {
                                        throw CreateFileMonitoringException(-2147024809, alias);
                                    }
                                    monitor2 = this.FindDirectoryMonitor(directoryOrRootName, true, true);
                                }
                                monitor = monitor2.StartMonitoringFileWithAssert(file, callback, alias);
                            }
                        }
                    }
Label_01C7:
                    if (!monitor.IsDirectory)
                    {
                        monitor.DirectoryMonitor.GetFileAttributes(file, out fad);
                    }
                    if (flag)
                    {
                        this._aliases[alias] = monitor;
                    }
                }
                finally
                {
                    this._lockDispose.ReleaseReaderLock();
                }
                if (fad != null)
                {
                    return(fad.UtcLastWriteTime);
                }
                return(DateTime.MinValue);
            }
        }
Ejemplo n.º 20
0
        //
        // constructor used by config section handler
        //
        internal CustomErrors(XmlNode node, String basePath, CustomErrors parent)
        {
            _mode = CustomErrorsMode.Off;

            // inherit parent settings

            if (parent != null)
            {
                _mode            = parent._mode;
                _defaultRedirect = parent._defaultRedirect;

                if (parent._codeRedirects != null)
                {
                    _codeRedirects = new Hashtable();
                    for (IDictionaryEnumerator e = parent._codeRedirects.GetEnumerator(); e.MoveNext();)
                    {
                        _codeRedirects.Add(e.Key, e.Value);
                    }
                }
            }

            // add current settings

            XmlNode a;
            String  redirect = null;

            // get default and mode from the main tag

            HandlerBase.GetAndRemoveStringAttribute(node, "defaultRedirect", ref redirect);

            if (redirect != null)
            {
                _defaultRedirect = GetAbsoluteRedirect(redirect, basePath);
            }

            int iMode = 0;

            a = HandlerBase.GetAndRemoveEnumAttribute(node, "mode", typeof(CustomErrorsMode), ref iMode);
            if (a != null)
            {
                _mode = (CustomErrorsMode)iMode;
            }

            // report errors on bad attribures
            HandlerBase.CheckForUnrecognizedAttributes(node);

            // child tags

            foreach (XmlNode child in node.ChildNodes)
            {
                if (HandlerBase.IsIgnorableAlsoCheckForNonElement(child))
                {
                    continue;
                }

                int status = 0; // set when req. attr. is read

                // only <error> is allowed

                if (child.Name != "error")
                {
                    HandlerBase.ThrowUnrecognizedElement(child);
                }

                // status code attribure

                a = HandlerBase.GetAndRemoveRequiredIntegerAttribute(child, "statusCode", ref status);
                if (status < 100 && status > 999)
                {
                    throw new ConfigurationException(
                              HttpRuntime.FormatResourceString(SR.Customerrors_invalid_statuscode),
                              a);
                }

                // redirect attribure
                redirect = HandlerBase.RemoveRequiredAttribute(child, "redirect");

                // errors on other attributes
                HandlerBase.CheckForUnrecognizedAttributes(child);
                // <error> tags contain no content
                HandlerBase.CheckForChildNodes(child);

                // remember

                if (_codeRedirects == null)
                {
                    _codeRedirects = new Hashtable();
                }

                _codeRedirects[status.ToString()] = GetAbsoluteRedirect(redirect, basePath);
            }
        }
Ejemplo n.º 21
0
 private void OnAppFileChange(object sender, FileChangeEvent e)
 {
     HttpRuntime.ShutdownAppDomain(ApplicationShutdownReason.ChangeInGlobalAsax, "Change in GLOBAL.ASAX");
 }
Ejemplo n.º 22
0
        public override SiteMapNode BuildSiteMap()
        {
            SiteMapNode node = this._siteMapNode;

            if (node != null)
            {
                return(node);
            }
            XmlDocument configDocument = this.GetConfigDocument();

            lock (base._lock)
            {
                if (this._siteMapNode == null)
                {
                    this.Clear();
                    this.CheckSiteMapFileExists();
                    try
                    {
                        using (Stream stream = this._normalizedVirtualPath.OpenFile())
                        {
                            XmlReader reader = new XmlTextReader(stream);
                            configDocument.Load(reader);
                        }
                    }
                    catch (XmlException exception)
                    {
                        string virtualPathString = this._virtualPath.VirtualPathString;
                        string path = this._normalizedVirtualPath.MapPathInternal();
                        if ((path != null) && HttpRuntime.HasPathDiscoveryPermission(path))
                        {
                            virtualPathString = path;
                        }
                        throw new ConfigurationErrorsException(System.Web.SR.GetString("XmlSiteMapProvider_Error_loading_Config_file", new object[] { this._virtualPath, exception.Message }), exception, virtualPathString, exception.LineNumber);
                    }
                    catch (Exception exception2)
                    {
                        throw new ConfigurationErrorsException(System.Web.SR.GetString("XmlSiteMapProvider_Error_loading_Config_file", new object[] { this._virtualPath, exception2.Message }), exception2);
                    }
                    XmlNode node2 = null;
                    foreach (XmlNode node3 in configDocument.ChildNodes)
                    {
                        if (string.Equals(node3.Name, "siteMap", StringComparison.Ordinal))
                        {
                            node2 = node3;
                            break;
                        }
                    }
                    if (node2 == null)
                    {
                        throw new ConfigurationErrorsException(System.Web.SR.GetString("XmlSiteMapProvider_Top_Element_Must_Be_SiteMap"), configDocument);
                    }
                    bool val = false;
                    System.Web.Configuration.HandlerBase.GetAndRemoveBooleanAttribute(node2, "enableLocalization", ref val);
                    base.EnableLocalization = val;
                    XmlNode node4 = null;
                    foreach (XmlNode node5 in node2.ChildNodes)
                    {
                        if (node5.NodeType == XmlNodeType.Element)
                        {
                            if (!"siteMapNode".Equals(node5.Name))
                            {
                                throw new ConfigurationErrorsException(System.Web.SR.GetString("XmlSiteMapProvider_Only_SiteMapNode_Allowed"), node5);
                            }
                            if (node4 != null)
                            {
                                throw new ConfigurationErrorsException(System.Web.SR.GetString("XmlSiteMapProvider_Only_One_SiteMapNode_Required_At_Top"), node5);
                            }
                            node4 = node5;
                        }
                    }
                    if (node4 == null)
                    {
                        throw new ConfigurationErrorsException(System.Web.SR.GetString("XmlSiteMapProvider_Only_One_SiteMapNode_Required_At_Top"), node2);
                    }
                    Queue queue = new Queue(50);
                    queue.Enqueue(null);
                    queue.Enqueue(node4);
                    this._siteMapNode = this.ConvertFromXmlNode(queue);
                }
                return(this._siteMapNode);
            }
        }
Ejemplo n.º 23
0
        public override SiteMapNode BuildSiteMap()
        {
            SiteMapNode tempNode = _siteMapNode;

            // If siteMap is already constructed, simply returns it.
            // Child providers will only be updated when the parent providers need to access them.
            if (tempNode != null)
            {
                return(tempNode);
            }

            XmlDocument document = GetConfigDocument();

            lock (_lock) {
                if (_siteMapNode != null)
                {
                    return(_siteMapNode);
                }

                Clear();

                // Need to check if the sitemap file exists before opening it.
                CheckSiteMapFileExists();

                try {
                    using (Stream stream = _normalizedVirtualPath.OpenFile()) {
                        XmlReader reader = new XmlTextReader(stream);
                        document.Load(reader);
                    }
                }
                catch (XmlException e) {
                    string sourceFile  = _virtualPath.VirtualPathString;
                    string physicalDir = _normalizedVirtualPath.MapPathInternal();
                    if (physicalDir != null && HttpRuntime.HasPathDiscoveryPermission(physicalDir))
                    {
                        sourceFile = physicalDir;
                    }

                    throw new ConfigurationErrorsException(
                              SR.GetString(SR.XmlSiteMapProvider_Error_loading_Config_file, _virtualPath, e.Message),
                              e, sourceFile, e.LineNumber);
                }
                catch (Exception e) {
                    throw new ConfigurationErrorsException(
                              SR.GetString(SR.XmlSiteMapProvider_Error_loading_Config_file, _virtualPath, e.Message), e);
                }

                XmlNode node = null;
                foreach (XmlNode siteMapMode in document.ChildNodes)
                {
                    if (String.Equals(siteMapMode.Name, "siteMap", StringComparison.Ordinal))
                    {
                        node = siteMapMode;
                        break;
                    }
                }

                if (node == null)
                {
                    throw new ConfigurationErrorsException(
                              SR.GetString(SR.XmlSiteMapProvider_Top_Element_Must_Be_SiteMap),
                              document);
                }

                bool enableLocalization = false;
                HandlerBase.GetAndRemoveBooleanAttribute(node, "enableLocalization", ref enableLocalization);
                EnableLocalization = enableLocalization;

                XmlNode topElement = null;
                foreach (XmlNode subNode in node.ChildNodes)
                {
                    if (subNode.NodeType == XmlNodeType.Element)
                    {
                        if (!_siteMapNodeName.Equals(subNode.Name))
                        {
                            throw new ConfigurationErrorsException(
                                      SR.GetString(SR.XmlSiteMapProvider_Only_SiteMapNode_Allowed),
                                      subNode);
                        }

                        if (topElement != null)
                        {
                            throw new ConfigurationErrorsException(
                                      SR.GetString(SR.XmlSiteMapProvider_Only_One_SiteMapNode_Required_At_Top),
                                      subNode);
                        }

                        topElement = subNode;
                    }
                }

                if (topElement == null)
                {
                    throw new ConfigurationErrorsException(
                              SR.GetString(SR.XmlSiteMapProvider_Only_One_SiteMapNode_Required_At_Top),
                              node);
                }

                Queue queue = new Queue(50);

                // The parentnode of the top node does not exist,
                // simply add a null to satisfy the ConvertFromXmlNode condition.
                queue.Enqueue(null);
                queue.Enqueue(topElement);
                _siteMapNode = ConvertFromXmlNode(queue);

                return(_siteMapNode);
            }
        }
Ejemplo n.º 24
0
 internal HttpRequestValidationException(string message)
     : base(message)
 {
     SetFormatter(new UnhandledErrorFormatter(
                      this, HttpRuntime.FormatResourceString(SR.Dangerous_input_detected_descr), null));
 }
        private void InitRequest()
        {
            int     num2;
            DataSet ds  = _masterRequest.Clone();
            DataRow row = this.NewRow(ds, "Trace_Request");

            row["Trace_Time_of_Request"] = this._context.Timestamp.ToString("G");
            string rawUrl = this._context.Request.RawUrl;
            int    index  = rawUrl.IndexOf("?", StringComparison.Ordinal);

            if (index != -1)
            {
                rawUrl = rawUrl.Substring(0, index);
            }
            row["Trace_Url"]          = rawUrl;
            row["Trace_Request_Type"] = this._context.Request.HttpMethod;
            try
            {
                row["Trace_Request_Encoding"] = this._context.Request.ContentEncoding.EncodingName;
            }
            catch
            {
            }
            if (this.TraceMode == System.Web.TraceMode.SortByCategory)
            {
                ds.Tables["Trace_Trace_Information"].DefaultView.Sort = "Trace_Category";
            }
            this.AddRow(ds, "Trace_Request", row);
            string[] allKeys = this._context.Request.Headers.AllKeys;
            for (num2 = 0; num2 < allKeys.Length; num2++)
            {
                row = this.NewRow(ds, "Trace_Headers_Collection");
                row["Trace_Name"]  = allKeys[num2];
                row["Trace_Value"] = this._context.Request.Headers[allKeys[num2]];
                this.AddRow(ds, "Trace_Headers_Collection", row);
            }
            ArrayList list = this._context.Response.GenerateResponseHeaders(false);
            int       num3 = (list != null) ? list.Count : 0;

            for (num2 = 0; num2 < num3; num2++)
            {
                HttpResponseHeader header = (HttpResponseHeader)list[num2];
                row = this.NewRow(ds, "Trace_Response_Headers_Collection");
                row["Trace_Name"]  = header.Name;
                row["Trace_Value"] = header.Value;
                this.AddRow(ds, "Trace_Response_Headers_Collection", row);
            }
            allKeys = this._context.Request.Form.AllKeys;
            for (num2 = 0; num2 < allKeys.Length; num2++)
            {
                row = this.NewRow(ds, "Trace_Form_Collection");
                row["Trace_Name"]  = allKeys[num2];
                row["Trace_Value"] = this._context.Request.Form[allKeys[num2]];
                this.AddRow(ds, "Trace_Form_Collection", row);
            }
            allKeys = this._context.Request.QueryString.AllKeys;
            for (num2 = 0; num2 < allKeys.Length; num2++)
            {
                row = this.NewRow(ds, "Trace_Querystring_Collection");
                row["Trace_Name"]  = allKeys[num2];
                row["Trace_Value"] = this._context.Request.QueryString[allKeys[num2]];
                this.AddRow(ds, "Trace_Querystring_Collection", row);
            }
            if (HttpRuntime.HasAppPathDiscoveryPermission())
            {
                allKeys = this._context.Request.ServerVariables.AllKeys;
                for (num2 = 0; num2 < allKeys.Length; num2++)
                {
                    row = this.NewRow(ds, "Trace_Server_Variables");
                    row["Trace_Name"]  = allKeys[num2];
                    row["Trace_Value"] = this._context.Request.ServerVariables.Get(allKeys[num2]);
                    this.AddRow(ds, "Trace_Server_Variables", row);
                }
            }
            this._requestData = ds;
        }
Ejemplo n.º 26
0
        /*  InitRequest
         *  Initialize the given dataset with basic
         *  request information
         */
        private void InitRequest()
        {
            // request info
            DataRow row = NewRow(_requestData, SR.Trace_Request);

            row[SR.Trace_Time_of_Request] = _context.Timestamp.ToString("G");

            string url = _context.Request.RawUrl;
            int    loc = url.IndexOf("?");

            if (loc != -1)
            {
                url = url.Substring(0, loc);
            }
            row[SR.Trace_Url] = url;

            row[SR.Trace_Request_Type] = _context.Request.HttpMethod;
            try {
                row[SR.Trace_Request_Encoding] = _context.Request.ContentEncoding.EncodingName;
            }
            catch {
                // if we get an exception getting the ContentEncoding, most likely
                // there's an error in the config file.  Just ignore it so we can finish InitRequest.
            }

            if (TraceMode == TraceMode.SortByCategory)
            {
                _requestData.Tables[SR.Trace_Trace_Information].DefaultView.Sort = SR.Trace_Category;
            }
            AddRow(_requestData, SR.Trace_Request, row);

            // header info
            int i;

            String[] keys = _context.Request.Headers.AllKeys;
            for (i = 0; i < keys.Length; i++)
            {
                row = NewRow(_requestData, SR.Trace_Headers_Collection);
                row[SR.Trace_Name]  = keys[i];
                row[SR.Trace_Value] = _context.Request.Headers[keys[i]];
                AddRow(_requestData, SR.Trace_Headers_Collection, row);
            }

            //form info
            keys = _context.Request.Form.AllKeys;
            for (i = 0; i < keys.Length; i++)
            {
                row = NewRow(_requestData, SR.Trace_Form_Collection);
                row[SR.Trace_Name]  = keys[i];
                row[SR.Trace_Value] = _context.Request.Form[keys[i]];
                AddRow(_requestData, SR.Trace_Form_Collection, row);
            }

            //QueryString info
            keys = _context.Request.QueryString.AllKeys;
            for (i = 0; i < keys.Length; i++)
            {
                row = NewRow(_requestData, SR.Trace_Querystring_Collection);
                row[SR.Trace_Name]  = keys[i];
                row[SR.Trace_Value] = _context.Request.QueryString[keys[i]];
                AddRow(_requestData, SR.Trace_Querystring_Collection, row);
            }

            //Server Variable info
            if (HttpRuntime.HasAppPathDiscoveryPermission())
            {
                keys = _context.Request.ServerVariables.AllKeys;
                for (i = 0; i < keys.Length; i++)
                {
                    row = NewRow(_requestData, SR.Trace_Server_Variables);
                    row[SR.Trace_Name]  = keys[i];
                    row[SR.Trace_Value] = _context.Request.ServerVariables.Get(keys[i]);
                    AddRow(_requestData, SR.Trace_Server_Variables, row);
                }
            }
        }
Ejemplo n.º 27
0
        internal /*public*/ string GetHtmlErrorMessage(bool dontShowSensitiveInfo)
        {
            // Give the formatter a chance to prepare its state
            PrepareFormatter();

            StringBuilder sb = new StringBuilder();

            // REVIEW: all the derived method should work directly with the string
            // builder instead of returning a string.

            sb.Append("<html>\r\n");
            sb.Append("    <head>\r\n");
            sb.Append("        <title>" + ErrorTitle + "</title>\r\n");
            sb.Append("        <style>\r\n");
            sb.Append("        	body {font-family:\"Verdana\";font-weight:normal;font-size: .7em;color:black;} \r\n");
            sb.Append("        	p {font-family:\"Verdana\";font-weight:normal;color:black;margin-top: -5px}\r\n");
            sb.Append("        	b {font-family:\"Verdana\";font-weight:bold;color:black;margin-top: -5px}\r\n");
            sb.Append("        	H1 { font-family:\"Verdana\";font-weight:normal;font-size:18pt;color:red }\r\n");
            sb.Append("        	H2 { font-family:\"Verdana\";font-weight:normal;font-size:14pt;color:maroon }\r\n");
            sb.Append("        	pre {font-family:\"Lucida Console\";font-size: .9em}\r\n");
            sb.Append("        	.marker {font-weight: bold; color: black;text-decoration: none;}\r\n");
            sb.Append("        	.version {color: gray;}\r\n");
            sb.Append("        	.error {margin-bottom: 10px;}\r\n");
            sb.Append("        	.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }\r\n");
            sb.Append("        </style>\r\n");
            sb.Append("    </head>\r\n\r\n");
            sb.Append("    <body bgcolor=\"white\">\r\n\r\n");
            sb.Append("            <span><H1>" + HttpRuntime.FormatResourceString(SR.Error_Formatter_ASPNET_Error, HttpRuntime.AppDomainAppVirtualPath) + "<hr width=100% size=1 color=silver></H1>\r\n\r\n");
            sb.Append("            <h2> <i>" + ErrorTitle + "</i> </h2></span>\r\n\r\n");
            sb.Append("            <font face=\"Arial, Helvetica, Geneva, SunSans-Regular, sans-serif \">\r\n\r\n");
            sb.Append("            <b> " + HttpRuntime.FormatResourceString(SR.Error_Formatter_Description) + " </b>" + Description + "\r\n");
            sb.Append("            <br><br>\r\n\r\n");
            if (MiscSectionTitle != null)
            {
                sb.Append("            <b> " + MiscSectionTitle + ": </b>" + MiscSectionContent + "<br><br>\r\n\r\n");
            }

            WriteColoredSquare(sb, ColoredSquareTitle, ColoredSquareDescription, ColoredSquareContent, WrapColoredSquareContentLines);

            if (ShowSourceFileInfo)
            {
                string fileName = HttpRuntime.GetSafePath(SourceFileName);
                if (fileName == null)
                {
                    fileName = HttpRuntime.FormatResourceString(SR.Error_Formatter_No_Source_File);
                }
                sb.Append("            <b> " + HttpRuntime.FormatResourceString(SR.Error_Formatter_Source_File) + " </b> " + fileName + "<b> &nbsp;&nbsp; " + HttpRuntime.FormatResourceString(SR.Error_Formatter_Line) + " </b> " + SourceFileLineNumber + "\r\n");
                sb.Append("            <br><br>\r\n\r\n");
            }

            // If it's a FileNotFoundException/FileLoadException/BadImageFormatException with a FusionLog,
            // write it out (ASURT 83587)
            if (!dontShowSensitiveInfo && Exception != null)
            {
                // (Only display the fusion log in medium or higher (ASURT 126827)
                if (HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium))
                {
                    for (Exception e = Exception; e != null; e = e.InnerException)
                    {
                        string fusionLog = null;
                        string filename  = null;
                        FileNotFoundException fnfException = e as FileNotFoundException;
                        if (fnfException != null)
                        {
                            fusionLog = fnfException.FusionLog;
                            filename  = fnfException.FileName;
                        }
                        FileLoadException flException = e as FileLoadException;
                        if (flException != null)
                        {
                            fusionLog = flException.FusionLog;
                            filename  = flException.FileName;
                        }
                        BadImageFormatException bifException = e as BadImageFormatException;
                        if (bifException != null)
                        {
                            fusionLog = bifException.FusionLog;
                            filename  = bifException.FileName;
                        }
                        if (fusionLog != null && fusionLog.Length > 0)
                        {
                            WriteColoredSquare(sb,
                                               HttpRuntime.FormatResourceString(SR.Error_Formatter_FusionLog),
                                               HttpRuntime.FormatResourceString(SR.Error_Formatter_FusionLogDesc, filename),
                                               HttpUtility.HtmlEncode(fusionLog),
                                               false /*WrapColoredSquareContentLines*/);
                            break;
                        }
                    }
                }
            }

            WriteColoredSquare(sb, ColoredSquare2Title, ColoredSquare2Description, ColoredSquare2Content, false);

            if (!dontShowSensitiveInfo)    // don't show version for security reasons
            {
                sb.Append("            <hr width=100% size=1 color=silver>\r\n\r\n");
                sb.Append("            <b>" + HttpRuntime.FormatResourceString(SR.Error_Formatter_Version) + "</b>&nbsp;" +
                          HttpRuntime.FormatResourceString(SR.Error_Formatter_CLR_Build) + VersionInfo.ClrVersion +
                          HttpRuntime.FormatResourceString(SR.Error_Formatter_ASPNET_Build) + VersionInfo.IsapiVersion + "\r\n\r\n");
                sb.Append("            </font>\r\n\r\n");
            }
            sb.Append("    </body>\r\n");
            sb.Append("</html>\r\n");

            sb.Append(PostMessage);

            return(sb.ToString());
        }
Ejemplo n.º 28
0
		static HttpRuntime ()
		{
			_runtime = new HttpRuntime ();
			_runtime.Init();
		}
 internal void OnFileChange(FileAction action, string fileName, DateTime utcCompletion)
 {
     try
     {
         FileMonitor        fileMon          = null;
         ArrayList          list             = null;
         FileAttributesData attributes       = null;
         FileAttributesData fad              = null;
         byte[]             dacl             = null;
         byte[]             buffer2          = null;
         FileAction         error            = FileAction.Error;
         DateTime           minValue         = DateTime.MinValue;
         bool fileMonitorForSpecialDirectory = false;
         if (this._dirMonCompletion != null)
         {
             lock (this)
             {
                 ICollection targets;
                 if (this._fileMons.Count > 0)
                 {
                     if ((action == FileAction.Error) || (action == FileAction.Overwhelming))
                     {
                         if (action == FileAction.Overwhelming)
                         {
                             HttpRuntime.SetShutdownMessage("Overwhelming Change Notification in " + this.Directory);
                             if (Interlocked.Increment(ref s_notificationBufferSizeIncreased) == 1)
                             {
                                 System.Web.UnsafeNativeMethods.GrowFileNotificationBuffer(HttpRuntime.AppDomainAppIdInternal, this._watchSubtree);
                             }
                         }
                         else if (action == FileAction.Error)
                         {
                             HttpRuntime.SetShutdownMessage("File Change Notification Error in " + this.Directory);
                         }
                         list = new ArrayList();
                         foreach (DictionaryEntry entry in this._fileMons)
                         {
                             string key = (string)entry.Key;
                             fileMon = (FileMonitor)entry.Value;
                             if ((fileMon.FileNameLong == key) && fileMon.Exists)
                             {
                                 fileMon.ResetCachedAttributes();
                                 fileMon.LastAction        = action;
                                 fileMon.UtcLastCompletion = utcCompletion;
                                 targets = fileMon.Targets;
                                 list.AddRange(targets);
                             }
                         }
                         fileMon = null;
                     }
                     else
                     {
                         fileMon = (FileMonitor)this._fileMons[fileName];
                         if (this._isDirMonAppPathInternal && (fileMon == null))
                         {
                             fileMonitorForSpecialDirectory = this.GetFileMonitorForSpecialDirectory(fileName, ref fileMon);
                         }
                         if (fileMon != null)
                         {
                             list                      = new ArrayList(fileMon.Targets);
                             attributes                = fileMon.Attributes;
                             dacl                      = fileMon.Dacl;
                             error                     = fileMon.LastAction;
                             minValue                  = fileMon.UtcLastCompletion;
                             fileMon.LastAction        = action;
                             fileMon.UtcLastCompletion = utcCompletion;
                             if ((action == FileAction.Removed) || (action == FileAction.RenamedOldName))
                             {
                                 fileMon.MakeExtinct();
                             }
                             else if (fileMon.Exists)
                             {
                                 if (minValue != utcCompletion)
                                 {
                                     fileMon.UpdateCachedAttributes();
                                 }
                             }
                             else
                             {
                                 int          num3;
                                 FindFileData data     = null;
                                 string       fullPath = Path.Combine(this.Directory, fileMon.FileNameLong);
                                 if (this._isDirMonAppPathInternal)
                                 {
                                     num3 = FindFileData.FindFile(fullPath, this.Directory, out data);
                                 }
                                 else
                                 {
                                     num3 = FindFileData.FindFile(fullPath, out data);
                                 }
                                 if (num3 == 0)
                                 {
                                     string fileNameShort = fileMon.FileNameShort;
                                     byte[] buffer3       = FileSecurity.GetDacl(fullPath);
                                     fileMon.MakeExist(data, buffer3);
                                     this.UpdateFileNameShort(fileMon, fileNameShort, data.FileNameShort);
                                 }
                             }
                             fad     = fileMon.Attributes;
                             buffer2 = fileMon.Dacl;
                         }
                     }
                 }
                 if (this._anyFileMon != null)
                 {
                     targets = this._anyFileMon.Targets;
                     if (list != null)
                     {
                         list.AddRange(targets);
                     }
                     else
                     {
                         list = new ArrayList(targets);
                     }
                 }
                 if ((action == FileAction.Error) || (action == FileAction.Overwhelming))
                 {
                     ((IDisposable)this).Dispose();
                 }
             }
             bool flag2 = false;
             if ((!fileMonitorForSpecialDirectory && (fileName != null)) && (action == FileAction.Modified))
             {
                 FileAttributesData data4 = fad;
                 if (data4 == null)
                 {
                     FileAttributesData.GetFileAttributes(Path.Combine(this.Directory, fileName), out data4);
                 }
                 if ((data4 != null) && ((data4.FileAttributes & FileAttributes.Directory) != 0))
                 {
                     flag2 = true;
                 }
             }
             if ((this._ignoreSubdirChange && ((action == FileAction.Removed) || (action == FileAction.RenamedOldName))) && (fileName != null))
             {
                 string str5 = Path.Combine(this.Directory, fileName);
                 if (!HttpRuntime.FileChangesMonitor.IsDirNameMonitored(str5, fileName))
                 {
                     flag2 = true;
                 }
             }
             if ((list != null) && !flag2)
             {
                 lock (s_notificationQueue.SyncRoot)
                 {
                     int num   = 0;
                     int count = list.Count;
                     while (num < count)
                     {
                         bool flag3;
                         FileMonitorTarget target = (FileMonitorTarget)list[num];
                         if (((action != FileAction.Added) && (action != FileAction.Modified)) || (fad == null))
                         {
                             flag3 = true;
                         }
                         else if (action == FileAction.Added)
                         {
                             flag3 = this.IsChangeAfterStartMonitoring(fad, target, utcCompletion);
                         }
                         else if (utcCompletion == minValue)
                         {
                             flag3 = error != FileAction.Modified;
                         }
                         else if (attributes == null)
                         {
                             flag3 = true;
                         }
                         else if ((dacl == null) || (dacl != buffer2))
                         {
                             flag3 = true;
                         }
                         else
                         {
                             flag3 = this.IsChangeAfterStartMonitoring(fad, target, utcCompletion);
                         }
                         if (flag3)
                         {
                             s_notificationQueue.Enqueue(new NotificationQueueItem(target.Callback, action, target.Alias));
                         }
                         num++;
                     }
                 }
                 if (((s_notificationQueue.Count > 0) && (s_inNotificationThread == 0)) && (Interlocked.Exchange(ref s_inNotificationThread, 1) == 0))
                 {
                     WorkItem.PostInternal(s_notificationCallback);
                 }
             }
         }
     }
     catch (Exception)
     {
     }
 }