I am using Visual Studio 2005 and IIS 6.0.. I have this warning in the event log. I am trying to find what it is. I have never went through this exception when i am working.
What can be done and where can be done to not get the exception warning again. Thanks so much in advance!!
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 10/13/2010 3:20:26 PM
Event time (UTC): 10/13/2010 7:20:26 PM
Event ID: fba7eb72412b4383a4c94bfcfd5c81a1
Event sequence: 708
Event occurrence: 6
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/568802591/Root-1-129314697219905000
Trust level: Full
Application Virtual Path: /
Application Path: C:\Inetpub\wwwroot\kjdfd.live\
Machine name: VME1053
Process information:
Process ID: 472
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
Request information:
Request URL: https://www.kjdfd.com:443/UserTownPage.aspx?tid=0
Request path: /UserTownPage.aspx
User host address: 173.188.124.86
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 11
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at UserTownPage.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Custom event details:
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Page Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SearchType = CommonHelper.SearchInnerType.Distance;
MakeActive(SearchType);
LoadData(true);
}
}
private void MakeActive(CommonHelper.SearchInnerType sType)
{
DealsActive.Attributes.Remove("class");
PopularActive.Attributes.Remove("class");
DistanceActive.Attributes.Remove("class");
AZActive.Attributes.Remove("class");
switch (sType)
{
case CommonHelper.SearchInnerType.A_Z:
AZActive.Attributes.Add("class", "current");
break;
case CommonHelper.SearchInnerType.Distance:
DistanceActive.Attributes.Add("class", "current");
break;
case CommonHelper.SearchInnerType.Popular:
PopularActive.Attributes.Add("class", "current");
break;
case CommonHelper.SearchInnerType.Deals:
DealsActive.Attributes.Add("class", "current");
break;
default:
AZActive.Attributes.Add("class", "current");
break;
}
}
private void LoadData(bool isSetPageIndex)
{
if (Session["keyword"] != null && Session["city"] != null && Session["state"] != null
&& Session["zipcode"] != null && Session["radius"] != null && Session["category"] != null)
{
string keyword = Session["keyword"].ToString();
string city = Session["city"].ToString();
string state = Session["state"].ToString();
string zipCode = Session["zipcode"].ToString();
double radius = Convert.ToDouble(Session["radius"].ToString());
int categoryID = Convert.ToInt32(Session["category"].ToString());
if (isSetPageIndex) PageIndex = 1;
DisplayRecords(keyword, city, state, zipCode, radius, categoryID, 1);
}
}
The problem appears to be a NullReferenceException is being thrown insed the Page_Load method of the UserTownPage type. More than that is not determinable from the information provided.
What you'll need to do is debug into that method and see exactly where the null reference is occuring.
Related
At first I'd like to say: Yes I know that there are many Questions that are similar to mine, but not the same.
When I start one of my 12 sites on my developer-machine everything works wonderful, and also on the server 11 of them work without a problem.
When I start the 12th site it first works fine, but when it cause a postback (Button, DropDownList with AutoPostBack, etc... ) I get the following error:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Infoscreen.Anzeigeeinstellungen.Page_Load(Object sender, EventArgs e) in C:\Users\Krusty\Desktop\Schule\Diplomarbeit\Infoscreen\Infoscreen\Anzeigeeinstellungen.aspx.cs:97
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +24
System.Web.UI.Control.LoadRecursive() +70
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3047
the path (C:\Users\Krusty\Desktop\Schule\Diplomarbeit\Infoscreen\Infoscreen\Anzeigeeinstellungen.aspx.cs) is the one where the file was on my developer-machine.
but why??
I never hardcoded any path in my program, and even recreating the site didn't work.
What shall i do? Any tips/hints would be appreciated.
EDIT:
91 if (!Page.IsPostBack)
92 {
93 Response.Cookies["Infoscreen_Anzeigeeinstellungen_Ausgewählte_Abteilung"].Value = ausgewählte_Abteilung.ToString();
94 }
95 else
96 {
97 ausgewählte_Abteilung = Request.Cookies["Infoscreen_Anzeigeeinstellungen_Ausgewählte_Abteilung"].Value;
98 }
EDIT:
Yes, IIS is configured to use Cookies
EDIT:
SOLVED!
in VisualStudio2010 Server the char 'ä' works...
in IIS7 it doesn't...
so the cookie never gets set propperly and the get request hangs up
named the cookie "Infoscreen_Anzeigeeinstellungen_Ausgewaehlte_Abteilung" and it works fine now
can be closed
As you already found out your self but just for future reference:
In your code for handling the cookie the 'name' is allowed in c# (using a-umlaut) but as per RFC2616 the token for a cookie MUST contain a subset of US-ASCII chars.
if (!Page.IsPostBack)
{
Response.Cookies["Infoscreen_Anzeigeeinstellungen_Ausgewählte_Abteilung"].Value = ausgewählte_Abteilung.ToString();
}
else
{
ausgewählte_Abteilung = Request.Cookies["Infoscreen_Anzeigeeinstellungen_Ausgewählte_Abteilung"].Value;
}
So a way to have a safe Cookies key in case your cookiekey is generated based on form/controlnames could be:
static string TokenRFC2616(string key)
{
const string separators = "()|<>#,;:\\\"/[]?={} ";
var chars = from ch in key.Normalize(NormalizationForm.FormD)
where CharUnicodeInfo.GetUnicodeCategory(ch)
!= UnicodeCategory.NonSpacingMark &&
separators.IndexOf(ch)==-1
select ch;
return String.Concat(chars);
}
string cookiekey = TokenRFC2616(
"Infoscreen_Anzeigeeinstellungen_Ausgewählte_Abteilung");
if (!Page.IsPostBack)
{
Response.Cookies[cookieKey].Value = ausgewählte_Abteilung.ToString();
}
else
{
ausgewählte_Abteilung = Request.Cookies[cookieKey].Value;
}
(in the above sample the cookie name will be Infoscreen_Anzeigeeinstellungen_Ausgewahlte_Abteilung
)
For testing purposes, I have this method:
public ActionResult Index()
{
System.Diagnostics.Debug.Write("Index");
return new HttpNotFoundResult();
}
The method is being called ('Index' is outputted). Somehow, it is causing a HttpException to be thrown. In my Global.asax file I have an Application_Error implementation:
void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
if (exc is System.Web.HttpException)
{
string msg = "UrlReferrer: "
+ Context.Request.UrlReferrer + " UserAgent: " + Context.Request.UserAgent
+ " UserHostAddress: " + Context.Request.UserHostAddress + " UserHostName: "
+ Context.Request.UserHostName;
ErrorHandler.Error(exc.Message, msg);
}
else {
...
}
}
This method is being called after the system has processed the request for Index. I think that the HttpNotFoundResult causes the exception to be thrown - or perhaps the exception is thrown for any ActionResult with a status code of 404.
This is quite annoying, as it is side-stepping the OnException handler on my controller. For my website, Application_Error is supposed to be a last-ditch fallback - most normal errors are intended to be handled in other places (by the controllers, or action filters). I only want Application_Error to log completely unexpected exceptions, or 404s for things like image or .js files.
Is there a way to stop asp.net from throwing exceptions for programatically generated 404s? Alternatively, is there a way to determine in Application_Error if the HttpException was caused by a programatically generated 404?
You can create a custom exception filter that handles 404 exceptions raised by all the actions. You could use HttpContext.Items collection to track whether it is a programatically raised 404 or not.
Custom exception filter
public class NotFoundExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// ignore if the exception is already handled or not a 404
if (filterContext.ExceptionHandled || new HttpException(null, filterContext.Exception).GetHttpCode() != 404)
return;
filterContext.HttpContext.Items.Add("Programmatic404", true);
filterContext.ExceptionHandled = true;
}
}
You need to apply NotFoundExceptionFilter as a global filter.
Application_Error event
public static void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
// ignore if it is a programatically raised 404
if(httpContext.Items["Programmatic404"] != null && bool.Parse(httpContext.Items["Programmatic404"].ToString()))
return;
// else, Log the exception
}
I am trying to rum my application and I am getting the following error as :
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.
The exception is thrown near the ** line of code:
public void LoadFromEntity(bool editable, string TabKey)
{
//Getting the FormMaster collection
**FormTemplate formTemplate = PolicyClassCollection.CachedPolicyClasses.FindBy((int)EnumPolicyClasses.PNI).FormTemplateCo**llection.Find(ft => ft.PolicyClassId == Utility.GetCurrentPolicyClassId() && ft.DocumentType.DocumentTypeId == (int)EnumDocumentTypes.Coverage_Summary && ft.PolicyTypeId == Utility.GetCurrentAccount().CurrentRisk.PolicyTypeId);
if (formTemplate != null)
{
//Set context string with current option number
this._Account.CurrentRisk.FormContextData = this.OptionNum.ToString();
//getting FormMasterID
Guid vsDatabaseId = formTemplate.FormFilingHistoryId;
string accountXmlString = this._Account.ToXML();
//Setting the parameters in PDFServiceParms class that are to be used in "PDFService.aspx" page.
PDFServiceParms pdfParams = new PDFServiceParms(FORM_MODE_EDIT, vsDatabaseId.ToString(), Model.AppConstants.FORM_TYPE_SELECTED_FORM, accountXmlString);
//Saving the parameters in the session. PDFService.aspx page reads the parameters from the session. Session key is passed in the
//query string when calling the PDFService.aspx page.
Session[AppConstants.SK_SUMMARY_PDF_PARAMS] = pdfParams;
//Setting the iFrame's source to PDFService.aspx page. The PDF document generated in this page is displayed in the iFrame.
this.iframePdf.Attributes["src"] = ResolveClientUrl(AppConstants.PAGE_NAME_PDFSERVICE) + "?datakey=" + AppConstants.SK_SUMMARY_PDF_PARAMS;
}
else
throw new ApplicationException("FormMaster not found for PolicyClass = " + Utility.GetCurrentPolicyClassId().ToString() + " and DocumentType = " + ((int)EnumDocumentTypes.Coverage_Summary).ToString());
}
Exception thrown:
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.ApplicationException: FormMaster not found for PolicyClass = 2 and DocumentType = 27
at PNI_SqbpeCovInfoPNISummary.LoadFromEntity(Boolean editable, String TabKey) in C:\TFS\Navigate Development\NavigateWebApp\PNI\SqbpeCovInfoPNISummary.aspx.cs:line 95
at SQBPECoverageInformationMasterPNI.LoadFromEntity() in C:\TFS\Navigate Development\NavigateWebApp\PNI\SQBPECoverageInformationMasterPNI.master.cs:line 188
at SQBPE.Page_Load(Object sender, EventArgs e) in C:\TFS\Navigate Development\NavigateWebApp\SQBPE.master.cs:line 55
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
--- End of inner exception stack trace ---
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.pni_sqbpecovinfopnisummary_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\navigatewebapp\253cae21\57ec5e1d\App_Web_sqbpecovinfopnisummary.aspx.41d7eb59.1z9y4p0a.0.cs:line 0
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
can some one please let me know what need to be done for this.
Sorry, edit of whole answer, previous was only halfway correct
The parent exception is a HttpUnhandledException. The internal exception seems quite clear and says:
FormMaster not found for PolicyClass = 2 and DocumentType = 27
That error is in your own code. The ApplicationException is not happening on the line you are referring to. The result of that line is that formTemplateis null and your code throws this exception.
This is the line throwing the exception:
throw new ApplicationException("FormMaster not found for PolicyClass = "
+ Utility.GetCurrentPolicyClassId().ToString()
+ " and DocumentType = "
+ ((int)EnumDocumentTypes.Coverage_Summary).ToString());
(a friendly tip, use string.Format instead)
And this is the line returning null:
FormTemplate formTemplate = PolicyClassCollection.CachedPolicyClasses
.FindBy((int)EnumPolicyClasses.PNI).FormTemplateCollection
.Find(ft => ft.PolicyClassId == Utility.GetCurrentPolicyClassId()
&& ft.DocumentType.DocumentTypeId == (int)EnumDocumentTypes.Coverage_Summary
&& ft.PolicyTypeId == Utility.GetCurrentAccount().CurrentRisk.PolicyTypeId);
(a friendly tip: write it out over multiple lines. That helps with setting breakpoints and with readability)
Your next question should be: why is it returning null? The answer, I don't know. In my previous attempt of answering I said something about third party code. And that's exactly what this is, as the class PolicyClassCollection is not a well-known class, there's no documentation on the internet on it. So either it is your own, in which case you can try stepping through (set a breakpoint) or it is someone else's in which case you can try calling the vendor or try stepping through after removing the "just my code" setting.
I am trying to code landing page which by reading Culture will decide whether request will be redirected to English site or Slovak site.
This is what the code looks like:
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strCountry = ResolveCountry().ToString();
if (strCountry == "SK")
{
Response.Redirect("/sk/");
}
else
{
Response.Redirect("/en/");
}
}
public static CultureInfo ResolveCulture()
{
string[] languages = HttpContext.Current.Request.UserLanguages;
if (languages == null || languages.Length == 0)
return null;
try
{
string language = languages[0].ToLowerInvariant().Trim();
return CultureInfo.CreateSpecificCulture(language);
}
catch (ArgumentException)
{
return null;
}
}
public static RegionInfo ResolveCountry()
{
CultureInfo culture = ResolveCulture();
if (culture != null)
return new RegionInfo(culture.LCID);
return null;
}
}
The problem is that in browser it looks ok, it redirects you to the site: http://www.alexmolcan.sk
But when checking IIS log, Google Webmaster tools or http://www.rexswain.com/httpview.html I always get 500 ASP Error:
Object·reference·not·set·to·an·instance·of·an·object.
System.NullReferenceException:·Object·reference·not·set·to·an·instance·of·an·object.
Response header:
HTTP/1.1·500·Internal·Server·Error
Connection:·close
Content-Length:·4684
When I debug project locally it always compile without any problems. I don't know what I do wrong
Thank you.
EDIT
Exception
Process information:
Process ID: 4068
Process name: w3wp.exe
Account name: IIS APPPOOL\ASP.NET v4.0
Exception information:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
at sk_alexmolcan._default.Page_Load(Object sender, EventArgs e) in default.aspx.cs:line 15
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I think you're throwing because when ResolveCountry returns null your .ToString() and if(strcountry == "SK") is going to throw.
Can't turn null into a string. try
CultureInfo cul = ResolveCountry();
string strCountry = cul== null ? string.empty : cul.ToString();
if (strCountry == "SK") {}
So in the Global.asax is this:
protected void Application_Error(object sender, System.EventArgs
{
Session["CustomError"] = Server.GetLastError();
Server.ClearError();
Response.Redirect("~/ErrorPage.aspx");
}
And in ErrorPage.aspx is this:
private void Page_Load(object sender, System.EventArgs e)
{
Exception currentException = ((Exception)Session["CustomError"]).InnerException;
// Writes the error message
if (currentException != null)
txtErrorMessage.Text = currentException.Message;
// Loops through the inner exceptions.
currentException = (Exception)Session["CustomError"];
while (currentException != null)
{
message.Append(currentException.Message).Append("\r\n").Append(currentException.StackTrace);
message.Append("\n==============================================\n");
currentException = currentException.InnerException;
}
As this is old 1.0 code it barfs when converted to a 3.5 Global.asax file. It tells me that "Session" is not available and also that I can't redirect?? I think one of the issues may be that there is also an error being thrown from Application_Start. But if I comment out all the application start code I still get errors but they never get redirected to the error page.
This link might help: Exceptional Gotchas!.
In addition, use the web.config file to define your default redirect page for errors.