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
)
Related
I know there are a lot of questions regarding this issue. But I am unable to solve my problem.
API Flow
It accepts two parameters meter serial number and date time.
After the parameters are passed the API call is made
The API will search for the sent meter serial number in two databases.
After the record is fetched it should give the output.
Code
Below is my code
public HttpResponseMessage GetDetails(string msn, DateTime dt)
{
try
{
var prodDetails = mdcEntitites.tj_xhqd.Where(m => m.sjsj >= dt)
.Select(x => new { MSN = x.zdjh, PingDateTime = x.sjsj, PingValue = x.xhqd })
.ToList();
var mainDetails = kesc.tj_xhqd.Where(m => m.sjsj >= dt)
.Select(x => new { MSN = x.zdjh,PingDateTime= x.sjsj,PingValue = x.xhqd })
.ToList();
var res = prodDetails.Concat(mainDetails).ToList();
return Request.CreateResponse(HttpStatusCode.OK, new {details = res });
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
In above call, I am accepting a date time. When a meter is dispatched to field staff the date time is marked in the system, so the above date is that date time.
It will search all the records of that serial number after this date time.
Error
Using Postman when I try to run the API with current date time it gives me the following result
{
"details": [
{
"MSN": "002998002523",
"PingDateTime": "2018-06-21T08:38:12",
"PingValue": "26"
},
{
"MSN": "002998001286",
"PingDateTime": "2018-06-21T08:38:13",
"PingValue": "18"
},
.
.
.
.
.
]
}
But when I try to run the API with date time less than current date time it gives me below exception
Exception of type 'System.OutOfMemoryException' was thrown.
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.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
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:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.IO.MemoryStream.set_Capacity(Int32 value) +89
System.IO.MemoryStream.EnsureCapacity(Int32 value) +90
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +326
Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +62
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +9746340
System.Web.HttpResponse.FilterOutput() +104
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +58
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +71
How can I get rid of this issue?
Any help would be highly appreciated.
As dlxeon points out, the PageInspector might be the cause of your exception. However you have a potential problem anyway: you are not limiting the number of search results that you are returning, and that might be an issue in the future when your database grows. You could do something like that:
Add an optional page parameter to your API call, and add something like .Skip((page-1)*PageSize).Take(PageSize) to your database query, right after the .Where. This is assuming that pages start at 1 and you have a PageSize constant defined.1
Include paging information in your response as needed by the client, e.g:
{
"pageSize": 10,
"currentPage": 1,
"details: "[
...
]
}
1In your case it will be a bit more complex since you are doing two database queries, but you get the idea.
I have a web service that should pull about 80 records from SQL database. However recently it started giving me out of memory error.
When I debug it - it shows me the web service on the list, once I run it - get the error below.
webmethod:
[WebMethod(Description = "Getting Weekly Events by Facility, future events from sunday", CacheDuration = 600)]
public List<EventViewModel> GetWeeklyEvents(string facilityNumber, DateTime StDate)
{
var db = new DS_AIMDataContext();
var eventList = from evt in db.GetPublishedEventsFromSundayByFacility(facilityNumber, StDate)
select new EventViewModel
{
EventName = evt.ActName,
EventNameSpanish = evt.ActNameSp,
EventDescription = evt.ActDescription,
EventDescrSpanish = evt.ActDescrSp,
StDate = evt.EventStart.Value,
EndDate = evt.EventEnd.Value,
EventCategory = evt.CategoryName,
EventCatID = evt.ActCategID.Value,
EventType = evt.ActType,
EventLocation = evt.LocName,
EventLeader = evt.LeaderName,
EventCategorySp = evt.CategoryNameSp,
EventTypeSp = evt.ActTypeSp,
EventRecurrenceRule = evt.RecurrenceRule,
EventPhoto1 = evt.Photo1 == null ? null : evt.Photo1.ToArray(),
EventPhoto2 = evt.Photo2 == null ? null : evt.Photo2.ToArray(),
EventPhoto3 = evt.Photo3 == null ? null : evt.Photo3.ToArray()
};
return eventList.ToList();
}
The function itself:
public IEnumerable<tblEventsWithRecurr> GetPublishedEventsFromSundayByFacility(string facN, DateTime StDate)
{
var eventList = from evt in this.tblEventsWithRecurrs
orderby Convert.ToDateTime(evt.EventStart.ToString()).Day, Convert.ToDateTime(evt.EventStart.ToString()).Hour, Convert.ToDateTime(evt.EventStart.ToString()).Minute
where (evt.FacN == facN && evt.EventStatus == "Final" && evt.EventStart >= StDate && evt.EventStart <= StDate.AddDays(31))
select evt;
return eventList;
}
Error that I'm getting is below:
Server Error in '/' Application.
Exception of type 'System.OutOfMemoryException' was thrown.
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.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
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:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.IO.MemoryStream.set_Capacity(Int32 value) +93
System.IO.MemoryStream.EnsureCapacity(Int32 value) +90
System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count) +326
Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.ArteryFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +61
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +9641608
System.Web.HttpResponse.FilterOutput() +104
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +58
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Couple of things:
First, how big are your Photo files - you have 3 photo's you're sending back. It would not be difficult to imagine a dozen very large photos on all of your results to max out whatever memory you have going on.
Secondly:
You may want to consider disposing of your datacontext.
Currently you have:
var db = new DS_AIMDataContext();
And this is never explicitly disposed, meaning the GC will eventually get to it, where you could instruct it to be disposed of the moment you are finished with it.
So try that line to:
using (DS_AIMDataContext db = new DS_AIMDataContext()){
// all of your eventList projection
// and your return statement
}
This will call Dispose as soon as your method completes and will hopefully free up memory.
I got assigned the task of resolving a problem where I suspect too much data is attempting to be written to the browser. I.e Building tables to display on 2,000+ records.
$exception {"Exception of type 'System.OutOfMemoryException' was thrown."} System.Exception {System.OutOfMemoryException}
Exception is thrown on Page_PreRender
What is the easiest way to troubleshoot the problem?
What is the easiest way to test/resolve it?
Thanks
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
System.String.Concat(String str0, String str1, String str2, String str3) +76
ProgramName.File.GetData() in C:\inetpub\wwwroot\ProgramName\File.aspx.cs:137
ProgramName.File.Page_PreRender(Object sender, EventArgs e) in C:\inetpub\wwwroot\ProgramName\File.aspx.cs:18
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnPreRender(EventArgs e) +8775110
System.Web.UI.Control.PreRenderRecursiveInternal() +80
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
With the stack trace I think I know your problem.
In your Page_PreRender method you are concatenating strings (you mention that you are constructing a table - it's likely that it's the code doing this).
If you concatenate 2 strings together, memory get's allocated to create a new string to hold the result, but the memory to store the first two strings does not get reclaimed because those strings are still in scope. I'm guessing that you are concatenating a lot of strings (in a loop), and thus are running out of memory.
The fix is to use a StringBuilder.
Find the code that looks something like this:
public void GetData()
{
string myTableString = "";
foreach (var row in MyRows)
{
myTableString += "<tr><td>" + row.someProperty + "</td></tr>"
}
to the following
using System.Text // This goes at the top of the file, with the other using statements.
...
public void GetData()
{
StringBuilder sb = new StringBuilder();
foreach (var row in MyRows)
{
sb.Append("<tr><td>" + row.someProperty + "</td></tr>");
}
string myTableString = sb.ToString();
Note that the code I've given above is just my best guess at what your code looks like - it would be much easier if you posted your code!!
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 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.