public void LoadControl_WithControlThrowingHttpParseException_LoadsErrorControlWithExceptionProperty() { // arrange var containerControl = new Mock <IContainerControl>(); var exception = new HttpParseException(); var userControl = new Mock <UserControl>(); userControl.Stub(c => c.ID); var errorControl = userControl.As <IErrorControl>(); userControl.Object.ID = "Foo.Bar"; errorControl.Stub(c => c.Exception); containerControl.Setup(tc => tc.LoadControl("~/Skins/VsShirts/Controls/ViewPost.ascx")).Throws(exception); containerControl.Setup(tc => tc.LoadControl("~/Skins/_System/Controls/Error.ascx")).Returns((UserControl)errorControl.Object); var skin = new SkinConfig { TemplateFolder = "VsShirts" }; var skinControlLoader = new SkinControlLoader(containerControl.Object, skin); // act var control = skinControlLoader.LoadControl("ViewPost") as IErrorControl; // assert Assert.AreEqual(exception, control.Exception.InnerException); }
private static void LogHttpParseException(HttpParseException ex, HttpContext context, RouteData routeData, BaseController controller) { int httpCode = ex.GetHttpCode(); string message = string.Empty; message = "Http Parse Exception " + httpCode + " \n-Message: " + ex.Message + " \n-Source: " + ex.Source + " \n-VirtualPath: " + ex.VirtualPath + " \n-FileName: " + ex.FileName + " (" + ex.Line + ")" + " \n-Parser Error Count: " + ex.ParserErrors.Count; int counter = 0; foreach (ParserError item in ex.ParserErrors) { counter++; string errorText = item.VirtualPath + " (" + item.Line + ") " + item.ErrorText; message += " \n-Parser Error [" + counter + "]: " + errorText; } message += " \n-Parser Errors: " + ex.ParserErrors.ToString() + " \n-WebEventCode: " + ex.WebEventCode + " \n-ErrorCode: " + ex.ErrorCode + " \n-TargetSiteName: " + ex.TargetSite.Name + " \n-StackTrace: " + ex.StackTrace + " Html Message: " + ex.GetHtmlErrorMessage(); LogException(message, ex, Models.SystemEventLevel.Error, context, routeData, controller); }
internal void Process() { this.AddBuildProviders(true); if (this._buildProviders.Count != 0) { BuildManager.ReportDirectoryCompilationProgress(this._vdir.VirtualPathObject); this.GetBuildResultDependencies(); this.ProcessDependencies(); ArrayList[] listArray = this._nonDependentBuckets; for (int i = 0; i < listArray.Length; i++) { ICollection buildProviders = listArray[i]; if (!this.CompileNonDependentBuildProviders(buildProviders)) { break; } } if ((this._parserErrors != null) && (this._parserErrors.Count > 0)) { HttpParseException exception = new HttpParseException(this._firstException.Message, this._firstException, this._firstException.VirtualPath, this._firstException.Source, this._firstException.Line); for (int j = 1; j < this._parserErrors.Count; j++) { exception.ParserErrors.Add(this._parserErrors[j]); } throw exception; } } }
public void Constructor5_Deny_Unrestricted() { HttpParseException e = new HttpParseException("message", new Exception(), "virtualPath", "sourceCode", 100); Assert.IsNull(e.FileName, "FileName"); Assert.AreEqual(100, e.Line, "Line"); Assert.AreEqual("virtualPath", e.VirtualPath, "VirtualPath"); Assert.AreEqual(1, e.ParserErrors.Count, "ParserErrors"); }
public void Constructor1_Deny_Unrestricted() { HttpParseException e = new HttpParseException("message"); Assert.IsNull(e.FileName, "FileName"); Assert.AreEqual(0, e.Line, "Line"); Assert.IsNull(e.VirtualPath, "VirtualPath"); Assert.AreEqual(1, e.ParserErrors.Count, "ParserErrors"); }
private void EmbedSourceCodeInformation(HttpParseException ex) { // Not showing source code of not related files if (!ex.FileName.StartsWith(PathUtil.Resolve(VirtualPath), StringComparison.OrdinalIgnoreCase)) { return; } string[] sourceCode = C1File.ReadAllLines(ex.FileName); XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, sourceCode, ex.Line); }
/// <summary> /// Formats HttpRequest attributes surrounding exception into an xml string /// </summary> private void FormatRequest(StringBuilder buf, HttpRequest request) { //record certain server variable info buf.Append("<ServerVariables>\r\n"); FormatNameValues("ServerVariable", buf, request.ServerVariables, "REMOTE_ADDR"); FormatNameValues("ServerVariable", buf, request.ServerVariables, "URL"); FormatNameValues("ServerVariable", buf, request.ServerVariables, "HTTP_HOST"); FormatNameValues("ServerVariable", buf, request.ServerVariables, "HTTP_USER_AGENT"); FormatNameValues("ServerVariable", buf, request.ServerVariables, "HTTP_REFERER"); buf.Append("</ServerVariables>\r\n"); //record querystring and form values buf.Append("<post-get>\r\n"); FormatNameValues("parameter", buf, request.Form); FormatNameValues("parameter", buf, request.QueryString); buf.Append("</post-get>\r\n"); //record cookies buf.Append("<cookies>\r\n"); String[] keys = request.Cookies.AllKeys; for (int i = 0; i < keys.Length; i++) { buf.Append("\t<cookie"); buf.Append(" key=\""); buf.Append(SafeXMLString(keys[i].Trim())); buf.Append("\" value=\""); buf.Append(SafeXMLString(request.Cookies.Get(keys[i]).Value)); buf.Append("\" />\r\n"); } buf.Append("</cookies>\r\n"); //record the html error string if (base.InnerException is HttpException) { buf.Append("<htmlMessage>\r\n"); buf.Append(SafeXMLString(((HttpException)base.InnerException).GetHtmlErrorMessage())); buf.Append("</htmlMessage>\r\n"); } //record parse exception stupp if (base.InnerException is HttpParseException) { HttpParseException parseException = (HttpParseException)base.InnerException; buf.Append("<fileName>"); buf.Append(parseException.FileName); buf.Append("</fileName>\r\n"); buf.Append("<lineNumber>"); buf.Append(parseException.Line); buf.Append("</lineNumber>\r\n"); } }
public static bool HandleHttpParseException(HttpParseException ex, bool clearError, HttpContext context, RouteData routeData, BaseController controller) { string rawUrl = context.Request.RawUrl; string url = context.Request.Url.ToString(); if (Settings.AppLogSystemEventsToDb || Settings.AppLogSystemEventsToFile) { LogHttpParseException(ex, context, routeData, controller); } if (Settings.AppUseFriendlyErrorPages) { ShowErrorPage(ErrorPage.Error_HttpError, ex.GetHttpCode(), ex, clearError, context, controller); return(true); } return(false); }
internal void Process() { AddBuildProviders(true /*retryIfDeletionHappens*/); // If there are no BuildProvider's, we're done if (_buildProviders.Count == 0) { return; } BuildManager.ReportDirectoryCompilationProgress(_vdir.VirtualPathObject); GetBuildResultDependencies(); ProcessDependencies(); foreach (ICollection buildProviders in _nonDependentBuckets) { if (!CompileNonDependentBuildProviders(buildProviders)) { break; } } // Report all parse exceptions if (_parserErrors != null && _parserErrors.Count > 0) { Debug.Assert(!_ignoreProvidersWithErrors); // Throw the first exception as inner exception along with the parse errors. HttpParseException newException = new HttpParseException(_firstException.Message, _firstException, _firstException.VirtualPath, _firstException.Source, _firstException.Line); // Add the rest of the parser errors to the exception. // The first one is already added. for (int i = 1; i < _parserErrors.Count; i++) { newException.ParserErrors.Add(_parserErrors[i]); } // rethrow the new exception throw newException; } }
static void DumpErrors(Exception exception) { // Check if one of the inner exceptions is more appropriate Exception e2 = GetFormattableException(exception); if (e2 != null) { exception = e2; } if (exception is HttpCompileException) { // NOTE: These are now handled by the callback #if OLD HttpCompileException e = (HttpCompileException)exception; DumpCompileErrors(e.Results); #endif } else if (exception is HttpParseException) { // NOTE: These are now handled by the callback #if OLD HttpParseException e = (HttpParseException)exception; DumpMultiParserErrors(e); #endif } else if (exception is ConfigurationException) { ConfigurationException e = (ConfigurationException)exception; DumpError(e.Filename, e.Line, false, "ASPCONFIG", e.BareMessage); } else { DumpError(null, 0, false, "ASPRUNTIME", exception.Message); } if (_showErrorStack) { DumpExceptionStack(exception); } }
public void LoadControl_WithControlThrowingHttpParseException_LoadsErrorControlWithExceptionHavingControlPath() { // arrange var containerControl = new Mock <IContainerControl>(); var exception = new HttpParseException(); var errorControl = new Error(); containerControl.Setup(tc => tc.LoadControl("~/Skins/OfMyChinnyChinChin/Controls/ViewPost.ascx")).Throws(exception); containerControl.Setup(tc => tc.LoadControl("~/Skins/_System/Controls/Error.ascx")).Returns(errorControl); var skin = new SkinConfig { TemplateFolder = "OfMyChinnyChinChin" }; var skinControlLoader = new SkinControlLoader(containerControl.Object, skin); // act var control = skinControlLoader.LoadControl("ViewPost") as IErrorControl; // assert Assert.AreEqual("~/Skins/OfMyChinnyChinChin/Controls/ViewPost.ascx", control.Exception.ControlPath); }
private bool CompileNonDependentBuildProviders(ICollection buildProviders) { IDictionary dictionary = new Hashtable(); ArrayList list = null; AssemblyBuilder builder = null; bool flag = false; foreach (System.Web.Compilation.BuildProvider provider in buildProviders) { ICollection is2; if (this.IsBuildProviderSkipable(provider)) { continue; } if (!BuildManager.ThrowOnFirstParseError) { InternalBuildProvider provider2 = provider as InternalBuildProvider; if (provider2 != null) { provider2.ThrowOnFirstParseError = false; } } CompilerType compilerTypeFromBuildProvider = null; try { compilerTypeFromBuildProvider = System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(provider); } catch (HttpParseException exception) { if (!this._ignoreProvidersWithErrors) { flag = true; if (this._firstException == null) { this._firstException = exception; } if (this._parserErrors == null) { this._parserErrors = new ParserErrorCollection(); } this._parserErrors.AddRange(exception.ParserErrors); } continue; } catch { if (!this._ignoreProvidersWithErrors) { throw; } continue; } AssemblyBuilder builder2 = builder; if (compilerTypeFromBuildProvider == null) { if (builder != null) { goto Label_00E6; } if (list == null) { list = new ArrayList(); } list.Add(provider); continue; } builder2 = (AssemblyBuilder)dictionary[compilerTypeFromBuildProvider]; Label_00E6: is2 = provider.GetGeneratedTypeNames(); if (((builder2 == null) || builder2.IsBatchFull) || builder2.ContainsTypeNames(is2)) { if (builder2 != null) { this.CompileAssemblyBuilder(builder2); } AssemblyBuilder builder3 = compilerTypeFromBuildProvider.CreateAssemblyBuilder(this._compConfig, this._referencedAssemblies); dictionary[compilerTypeFromBuildProvider] = builder3; if ((builder == null) || (builder == builder2)) { builder = builder3; } builder2 = builder3; } builder2.AddTypeNames(is2); builder2.AddBuildProvider(provider); } if (flag) { return(false); } if (list != null) { bool flag2 = builder == null; foreach (System.Web.Compilation.BuildProvider provider3 in list) { ICollection generatedTypeNames = provider3.GetGeneratedTypeNames(); if (((builder == null) || builder.IsBatchFull) || builder.ContainsTypeNames(generatedTypeNames)) { if (builder != null) { this.CompileAssemblyBuilder(builder); } builder = CompilerType.GetDefaultAssemblyBuilder(this._compConfig, this._referencedAssemblies, this._vdir.VirtualPathObject, null); flag2 = true; } builder.AddTypeNames(generatedTypeNames); builder.AddBuildProvider(provider3); } if (flag2) { this.CompileAssemblyBuilder(builder); } } foreach (AssemblyBuilder builder4 in dictionary.Values) { this.CompileAssemblyBuilder(builder4); } return(true); }
/* * Parse the contents of the string, and catch exceptions */ internal void ParseString(string text, VirtualPath virtualPath, Encoding fileEncoding) { System.Web.Util.Debug.Trace("Template", "Starting parse at " + DateTime.Now); // Save the previous base dirs and line number VirtualPath prevVirtualPath = CurrentVirtualPath; int prevLineNumber = _lineNumber; // Set the new current base dirs and line number CurrentVirtualPath = virtualPath; _lineNumber = 1; // Always ignore the spaces at the beginning of a string flags[ignoreNextSpaceString] = true; try { ParseStringInternal(text, fileEncoding); // If there are parser errors caught in the parser if (HasParserErrors) { ParserError firstError = ParserErrors[0]; Exception originalException = firstError.Exception; // Use the first error as the inner exception if not already caught one. if (originalException == null) { originalException = new HttpException(firstError.ErrorText); } // Make it a HttpParseException with proper info. HttpParseException ex = new HttpParseException(firstError.ErrorText, originalException, firstError.VirtualPath, Text, firstError.Line); // Add the rest of the errors for (int i = 1; i < ParserErrors.Count; i++) { ex.ParserErrors.Add(ParserErrors[i]); } // throw the new exception throw ex; } // Make sure that if any code calls ProcessError/ProcessException after this point, // it throws the error right away, since we won't look at ParserErrors/_firstParseException // anymore ThrowOnFirstParseError = true; } catch (Exception e) { ErrorFormatter errorFormatter = null; PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_PRE_PROCESSING); PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL); // Check if the exception has a formatter errorFormatter = HttpException.GetErrorFormatter(e); // If it doesn't, throw a parse exception if (errorFormatter == null) { throw new HttpParseException(e.Message, e, CurrentVirtualPath, text, _lineNumber); } else { // Otherwise, just rethrow it throw; } } finally { // Restore the previous base dirs and line number CurrentVirtualPath = prevVirtualPath; _lineNumber = prevLineNumber; } System.Web.Util.Debug.Trace("Template", "Ending parse at " + DateTime.Now); }
private bool CompileNonDependentBuildProviders(ICollection buildProviders) { // Key: CompilerType, Value: AssemblyBuilder IDictionary assemblyBuilders = new Hashtable(); // List of InternalBuildProvider's that don't ask for a specific language ArrayList languageFreeBuildProviders = null; // AssemblyBuilder used for providers that don't need a specific language AssemblyBuilder defaultAssemblyBuilder = null; bool hasParserErrors = false; foreach (BuildProvider buildProvider in buildProviders) { if (IsBuildProviderSkipable(buildProvider)) continue; // Instruct the internal build providers to continue processing for more parse errors. if (!BuildManager.ThrowOnFirstParseError) { InternalBuildProvider provider = buildProvider as InternalBuildProvider; if (provider != null) { provider.ThrowOnFirstParseError = false; } } CompilerType compilerType = null; // Get the language try { compilerType = BuildProvider.GetCompilerTypeFromBuildProvider( buildProvider); } catch (HttpParseException ex) { // Ignore the error if we are in that mode. if (_ignoreProvidersWithErrors) { continue; } hasParserErrors = true; // Remember the first parse exception if (_firstException == null) { _firstException = ex; } if (_parserErrors == null) { _parserErrors = new ParserErrorCollection(); } _parserErrors.AddRange(ex.ParserErrors); continue; } catch { // Ignore the error if we are in that mode. if (_ignoreProvidersWithErrors) { continue; } throw; } AssemblyBuilder assemblyBuilder = defaultAssemblyBuilder; ICollection typeNames = buildProvider.GetGeneratedTypeNames(); // Is it asking for a specific language? if (compilerType == null) { // If this provider doesn't need a specific language, and we haven't yet created // a default builder that is capable of building this, just keep track of it if (defaultAssemblyBuilder == null || defaultAssemblyBuilder.IsBatchFull || defaultAssemblyBuilder.ContainsTypeNames(typeNames)) { if (languageFreeBuildProviders == null) { languageFreeBuildProviders = new ArrayList(); } languageFreeBuildProviders.Add(buildProvider); continue; } } else { // Check if we already have an assembly builder of the right type assemblyBuilder = (AssemblyBuilder)assemblyBuilders[compilerType]; } // Starts a new assemblyBuilder if the old one already contains another buildprovider // that uses the same type name if (assemblyBuilder == null || assemblyBuilder.IsBatchFull || assemblyBuilder.ContainsTypeNames(typeNames)) { // If the assemblyBuilder is full, compile it. if (assemblyBuilder != null) { CompileAssemblyBuilder(assemblyBuilder); } AssemblyBuilder newBuilder = compilerType.CreateAssemblyBuilder( _compConfig, _referencedAssemblies); assemblyBuilders[compilerType] = newBuilder; // Remember it as the default if we don't already have one, // or if the default is already full, switch the default to the new one. if (defaultAssemblyBuilder == null || defaultAssemblyBuilder == assemblyBuilder) { defaultAssemblyBuilder = newBuilder; } assemblyBuilder = newBuilder; } assemblyBuilder.AddTypeNames(typeNames); assemblyBuilder.AddBuildProvider(buildProvider); } // Don't try to compile providers, otherwise compile exceptions will be bubbled up, // and we lose the parse errors. if (hasParserErrors) { return false; } // Handle all the left over language free providers if (languageFreeBuildProviders != null) { // Indicates whether the default assembly builder is not a language specific builder. bool newDefaultAssemblyBuilder = (defaultAssemblyBuilder == null); // Add language independent providers to the default assembly builder. foreach (BuildProvider languageFreeBuildProvider in languageFreeBuildProviders) { ICollection typeNames = languageFreeBuildProvider.GetGeneratedTypeNames(); // If we don't have a default language assembly builder, get one or // starts a new assemblyBuilder if the old one already contains another buildprovider // that uses the same type name if (defaultAssemblyBuilder == null || defaultAssemblyBuilder.IsBatchFull || defaultAssemblyBuilder.ContainsTypeNames(typeNames)) { // If the default assemblyBuilder is full, compile it. if (defaultAssemblyBuilder != null) { CompileAssemblyBuilder(defaultAssemblyBuilder); } defaultAssemblyBuilder = CompilerType.GetDefaultAssemblyBuilder( _compConfig, _referencedAssemblies, _vdir.VirtualPathObject /*configPath*/, null /*outputAssemblyName*/); // the default assembly builder needs to be compiled separately. newDefaultAssemblyBuilder = true; } defaultAssemblyBuilder.AddTypeNames(typeNames); defaultAssemblyBuilder.AddBuildProvider(languageFreeBuildProvider); } // Only compile the default assembly builder if it's not part of language specific // assembly builder (which will be compiled separately) if (newDefaultAssemblyBuilder) { // Compile the default assembly builder. CompileAssemblyBuilder(defaultAssemblyBuilder); } } CompileAssemblyBuilderParallel(assemblyBuilders.Values); return true; }
internal void Process() { AddBuildProviders(true /*retryIfDeletionHappens*/); // If there are no BuildProvider's, we're done if (_buildProviders.Count == 0) return; BuildManager.ReportDirectoryCompilationProgress(_vdir.VirtualPathObject); GetBuildResultDependencies(); ProcessDependencies(); foreach (ICollection buildProviders in _nonDependentBuckets) { if (!CompileNonDependentBuildProviders(buildProviders)) break; } // Report all parse exceptions if (_parserErrors != null && _parserErrors.Count > 0) { Debug.Assert(!_ignoreProvidersWithErrors); // Throw the first exception as inner exception along with the parse errors. HttpParseException newException = new HttpParseException(_firstException.Message, _firstException, _firstException.VirtualPath, _firstException.Source, _firstException.Line); // Add the rest of the parser errors to the exception. // The first one is already added. for (int i = 1; i < _parserErrors.Count; i++) { newException.ParserErrors.Add(_parserErrors[i]); } // rethrow the new exception throw newException; } }
protected virtual void ExceptionHandler(ExceptionContext filterContext) { if (!filterContext.ExceptionHandled) { if (filterContext.Exception.GetBaseException() is DynamicPageInactiveException) { DynamicPageInactiveException exDPI = filterContext.Exception.GetBaseException() as DynamicPageInactiveException; filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleDynamicPageInactiveException(exDPI, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception.GetBaseException() is DynamicPageNotFoundException) { DynamicPageNotFoundException exDPNF = filterContext.Exception.GetBaseException() as DynamicPageNotFoundException; filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleDynamicPageNotFoundException(exDPNF, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception.GetBaseException() is NoMatchingBindingException) { NoMatchingBindingException exNMB = filterContext.Exception.GetBaseException() as NoMatchingBindingException; filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleNoMatchingBindingException(exNMB, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception.GetBaseException() is StoreFrontInactiveException) { StoreFrontInactiveException exSFI = filterContext.Exception.GetBaseException() as StoreFrontInactiveException; filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleStoreFrontInactiveException(exSFI, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception is HttpCompileException || filterContext.Exception.GetBaseException() is HttpCompileException) { HttpCompileException httpCompileEx = null; if (filterContext.Exception is HttpCompileException) { httpCompileEx = filterContext.Exception as HttpCompileException; } else { httpCompileEx = filterContext.Exception.GetBaseException() as HttpCompileException; } filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleHttpCompileException(httpCompileEx, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception is HttpParseException || filterContext.Exception.GetBaseException() is HttpParseException) { HttpParseException httpParseEx = null; if (filterContext.Exception is HttpCompileException) { httpParseEx = filterContext.Exception as HttpParseException; } else { httpParseEx = filterContext.Exception.GetBaseException() as HttpParseException; } filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleHttpParseException(httpParseEx, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception is HttpException || filterContext.Exception.GetBaseException() is HttpException) { HttpException httpEx = null; if (filterContext.Exception is HttpException) { httpEx = filterContext.Exception as HttpException; } else { httpEx = filterContext.Exception.GetBaseException() as HttpException; } filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleHttpException(httpEx, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception is ApplicationException) { ApplicationException appEx = filterContext.Exception as ApplicationException; filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleAppException(appEx, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } else if (filterContext.Exception is InvalidOperationException || filterContext.Exception.GetBaseException() is InvalidOperationException) { InvalidOperationException ioEx = null; if (filterContext.Exception is InvalidOperationException) { ioEx = filterContext.Exception as InvalidOperationException; } else { ioEx = filterContext.Exception.GetBaseException() as InvalidOperationException; } filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleInvalidOperationException(ioEx, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } //Unknown exception handler //exceptions that are expected or common should hit the above exception handlers. Exception ex = filterContext.Exception; filterContext.ExceptionHandled = Exceptions.ExceptionHandler.HandleUnknownException(ex, false, filterContext.HttpContext.ApplicationInstance.Context, RouteData, this); return; } }
internal MobileErrorInfo(Exception e) { // Don't want any failure to escape here... try { // For some reason, the compile exception lives in the // InnerException. HttpCompileException compileException = e.InnerException as HttpCompileException; if (compileException != null) { this.Type = SR.GetString(SR.MobileErrorInfo_CompilationErrorType); this.Description = SR.GetString(SR.MobileErrorInfo_CompilationErrorDescription); this.MiscTitle = SR.GetString(SR.MobileErrorInfo_CompilationErrorMiscTitle); CompilerErrorCollection errors = compileException.Results.Errors; if (errors != null && errors.Count >= 1) { CompilerError error = errors[0]; this.LineNumber = error.Line.ToString(CultureInfo.InvariantCulture); this.File = error.FileName; this.MiscText = error.ErrorNumber + ":" + error.ErrorText; } else { this.LineNumber = SR.GetString(SR.MobileErrorInfo_Unknown); this.File = SR.GetString(SR.MobileErrorInfo_Unknown); this.MiscText = SR.GetString(SR.MobileErrorInfo_Unknown); } return; } HttpParseException parseException = e as HttpParseException; if (parseException != null) { this.Type = SR.GetString(SR.MobileErrorInfo_ParserErrorType); this.Description = SR.GetString(SR.MobileErrorInfo_ParserErrorDescription); this.MiscTitle = SR.GetString(SR.MobileErrorInfo_ParserErrorMiscTitle); this.LineNumber = parseException.Line.ToString(CultureInfo.InvariantCulture); this.File = parseException.FileName; this.MiscText = parseException.Message; return; } // We try to use the hacky way of parsing an HttpException of an // unknown subclass. HttpException httpException = e as HttpException; if (httpException != null && ParseHttpException(httpException)) { return; } } catch { // Don't need to do anything here, just continue to base case // below. } // Default to the most basic if none of the above succeed. this.Type = e.GetType().FullName; this.Description = e.Message; this.MiscTitle = SR.GetString(SR.MobileErrorInfo_SourceObject); String s = e.StackTrace; if (s != null) { int i = s.IndexOf('\r'); if (i != -1) { s = s.Substring(0, i); } this.MiscText = s; } }
public void FixtureSetUp() { hpe = new HttpParseException(); }
/// <summary> /// Parses a job. /// </summary> /// <param name="sourceData">The source data for the job.</param> /// <returns></returns> public Job ParseJob(string sourceData, string jobId) { HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument(); htmlDocument.OptionFixNestedTags = true; htmlDocument.LoadHtml(sourceData); // ParseErrors is an ArrayList containing any errors from the Load statement if (htmlDocument.ParseErrors != null && htmlDocument.ParseErrors.Count() > 0) { foreach (var error in htmlDocument.ParseErrors) { var exception = new HttpParseException("Unable to parse job HTML from TalentLink"); exception.Data.Add("Job ID", jobId); exception.Data.Add("Type of error", error.Code); exception.Data.Add("Reason", error.Reason); exception.Data.Add("Line", error.Line); exception.Data.Add("Position on line", error.LinePosition); exception.Data.Add("Source HTML", error.SourceText); exception.ToExceptionless().Submit(); } return(null); } else { if (htmlDocument.DocumentNode != null) { var job = new Job(); job.JobTitle = ParseValueFromElementById(htmlDocument, "h3", "JDText-Title"); job.Reference = ParseValueFromElementById(htmlDocument, "span", "JDText-Param2"); if (!String.IsNullOrEmpty(job.Reference)) { job.JobTitle = job.JobTitle.Replace(" (" + job.Reference + ")", String.Empty); } job.Location = ParseValueFromElementById(htmlDocument, "span", "JDText-Param3"); job.Organisation = ParseValueFromElementById(htmlDocument, "span", "JDText-Param4"); job.Department = ParseValueFromElementById(htmlDocument, "span", "JDText-Param5"); job.ContractType = ParseValueFromElementById(htmlDocument, "span", "JDText-Param6"); job.JobType = ParseValueFromElementById(htmlDocument, "span", "JDText-Param7"); job.Salary = _salaryParser.ParseSalaryFromHtml(htmlDocument); DateTime closingDate; DateTime.TryParse(ParseValueFromElementById(htmlDocument, "span", "JDText-Param9"), new CultureInfo("en-GB"), DateTimeStyles.AssumeLocal, out closingDate); job.ClosingDate = closingDate; var agilityPackFormatters = new IHtmlAgilityPackHtmlFormatter[] { new RemoveUnwantedAttributesFormatter(new string[] { "style" }), new ReplaceElementNameFormatter("h5", "h2"), new RemoveElementByNameAndContentFormatter("h2", "Job Details"), }; foreach (var formatter in agilityPackFormatters) { formatter.FormatHtml(htmlDocument); } var additionalInfo = ParseValueFromElementById(htmlDocument, "span", "JDText-Field4"); if (!String.IsNullOrEmpty(additionalInfo)) { additionalInfo = ApplyStringFormatters(additionalInfo); job.AdditionalInformationHtml = new HtmlString(additionalInfo); } var equalOpportunities = ParseValueFromElementById(htmlDocument, "span", "JDText-Field5"); if (!String.IsNullOrEmpty(equalOpportunities)) { equalOpportunities = ApplyStringFormatters(equalOpportunities); job.EqualOpportunitiesHtml = new HtmlString(equalOpportunities); } var parsedHtml = ParseValueFromElementById(htmlDocument, "div", "JD-Field1") + Environment.NewLine + ParseValueFromElementById(htmlDocument, "div", "JD-Field2") + Environment.NewLine + ParseValueFromElementById(htmlDocument, "div", "JD-Field6") + Environment.NewLine + ParseValueFromElementById(htmlDocument, "div", "JD-Documents"); parsedHtml = ApplyStringFormatters(parsedHtml); parsedHtml = new RemoveDuplicateTextFormatter("Closing date: " + job.ClosingDate.Value.ToBritishDateWithDay()).FormatHtml(parsedHtml); job.AdvertHtml = new HtmlString(parsedHtml); job.WorkPattern = _workPatternParser.ParseWorkPatternFromHtml(parsedHtml); var applyLink = htmlDocument.DocumentNode.SelectSingleNode($"//div[@id='JD-ActApplyDirect']/a"); if (applyLink != null) { job.ApplyUrl = new Uri(HttpUtility.HtmlDecode(applyLink.Attributes["href"].Value), UriKind.RelativeOrAbsolute); } return(job); } return(null); } }
private bool CompileNonDependentBuildProviders(ICollection buildProviders) { // Key: CompilerType, Value: AssemblyBuilder IDictionary assemblyBuilders = new Hashtable(); // List of InternalBuildProvider's that don't ask for a specific language ArrayList languageFreeBuildProviders = null; // AssemblyBuilder used for providers that don't need a specific language AssemblyBuilder defaultAssemblyBuilder = null; bool hasParserErrors = false; foreach (BuildProvider buildProvider in buildProviders) { if (IsBuildProviderSkipable(buildProvider)) { continue; } // Instruct the internal build providers to continue processing for more parse errors. if (!BuildManager.ThrowOnFirstParseError) { InternalBuildProvider provider = buildProvider as InternalBuildProvider; if (provider != null) { provider.ThrowOnFirstParseError = false; } } CompilerType compilerType = null; // Get the language try { compilerType = BuildProvider.GetCompilerTypeFromBuildProvider( buildProvider); } catch (HttpParseException ex) { // Ignore the error if we are in that mode. if (_ignoreProvidersWithErrors) { continue; } hasParserErrors = true; // Remember the first parse exception if (_firstException == null) { _firstException = ex; } if (_parserErrors == null) { _parserErrors = new ParserErrorCollection(); } _parserErrors.AddRange(ex.ParserErrors); continue; } catch { // Ignore the error if we are in that mode. if (_ignoreProvidersWithErrors) { continue; } throw; } AssemblyBuilder assemblyBuilder = defaultAssemblyBuilder; ICollection typeNames = buildProvider.GetGeneratedTypeNames(); // Is it asking for a specific language? if (compilerType == null) { // If this provider doesn't need a specific language, and we haven't yet created // a default builder that is capable of building this, just keep track of it if (defaultAssemblyBuilder == null || defaultAssemblyBuilder.IsBatchFull || defaultAssemblyBuilder.ContainsTypeNames(typeNames)) { if (languageFreeBuildProviders == null) { languageFreeBuildProviders = new ArrayList(); } languageFreeBuildProviders.Add(buildProvider); continue; } } else { // Check if we already have an assembly builder of the right type assemblyBuilder = (AssemblyBuilder)assemblyBuilders[compilerType]; } // Starts a new assemblyBuilder if the old one already contains another buildprovider // that uses the same type name if (assemblyBuilder == null || assemblyBuilder.IsBatchFull || assemblyBuilder.ContainsTypeNames(typeNames)) { // If the assemblyBuilder is full, compile it. if (assemblyBuilder != null) { CompileAssemblyBuilder(assemblyBuilder); } AssemblyBuilder newBuilder = compilerType.CreateAssemblyBuilder( _compConfig, _referencedAssemblies); assemblyBuilders[compilerType] = newBuilder; // Remember it as the default if we don't already have one, // or if the default is already full, switch the default to the new one. if (defaultAssemblyBuilder == null || defaultAssemblyBuilder == assemblyBuilder) { defaultAssemblyBuilder = newBuilder; } assemblyBuilder = newBuilder; } assemblyBuilder.AddTypeNames(typeNames); assemblyBuilder.AddBuildProvider(buildProvider); } // Don't try to compile providers, otherwise compile exceptions will be bubbled up, // and we lose the parse errors. if (hasParserErrors) { return(false); } // Handle all the left over language free providers if (languageFreeBuildProviders != null) { // Indicates whether the default assembly builder is not a language specific builder. bool newDefaultAssemblyBuilder = (defaultAssemblyBuilder == null); // Add language independent providers to the default assembly builder. foreach (BuildProvider languageFreeBuildProvider in languageFreeBuildProviders) { ICollection typeNames = languageFreeBuildProvider.GetGeneratedTypeNames(); // If we don't have a default language assembly builder, get one or // starts a new assemblyBuilder if the old one already contains another buildprovider // that uses the same type name if (defaultAssemblyBuilder == null || defaultAssemblyBuilder.IsBatchFull || defaultAssemblyBuilder.ContainsTypeNames(typeNames)) { // If the default assemblyBuilder is full, compile it. if (defaultAssemblyBuilder != null) { CompileAssemblyBuilder(defaultAssemblyBuilder); } defaultAssemblyBuilder = CompilerType.GetDefaultAssemblyBuilder( _compConfig, _referencedAssemblies, _vdir.VirtualPathObject /*configPath*/, null /*outputAssemblyName*/); // the default assembly builder needs to be compiled separately. newDefaultAssemblyBuilder = true; } defaultAssemblyBuilder.AddTypeNames(typeNames); defaultAssemblyBuilder.AddBuildProvider(languageFreeBuildProvider); } // Only compile the default assembly builder if it's not part of language specific // assembly builder (which will be compiled separately) if (newDefaultAssemblyBuilder) { // Compile the default assembly builder. CompileAssemblyBuilder(defaultAssemblyBuilder); } } CompileAssemblyBuilderParallel(assemblyBuilders.Values); return(true); }