ASP.Net String Assignment Failure - asp.net

This is my first post here, so go easy on me :) I'm having an odd problem with an ASP.Net page. I'm getting an object not set error message when assigning a string literal to a variable. Here's the error I'm getting.
[NullReferenceException: Object
reference not set to an instance of an
object.]
Project.Page.Page_Load(Object sender,
EventArgs e) in
C:\Project\Page.aspx.vb:10
System.Web.UI.Control.OnLoad(EventArgs
e) +91
System.Web.UI.Control.LoadRecursive()
+74 System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +2207
And here is the code that the error is pointing to. The last line in this fragment is the line 10 the error is complaining about
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim teststring As String
teststring = "test"
It seems it fails on accessing any reference type, even if it is declared locally in the load function. I originally found the problem when Request.IsSecureConnection was nulling out on me. I eventually discovered I could replace it with the above code and fail in the same way.
The problem does not always happen. It seems to be triggered by publishing an update from Visual Studio, or when I head home for the day and the server sits idle all night. One or two app pool recycles seems to clear it up, and the page functions correctly.
Any help would be greatly appreciated. I've been doing desktop development for a few years, but I'm fairly new to web development. So maybe this is something obvious I've got configured wrong. I'm currently using .Net 4 on IIS 6.
UPDATE
I was able to identify the line using the recommendation of copying the page, commenting everything out, and then uncommenting one line at a time. The line my test page started giving the error was this one
Dim StateName As String = State.Attribute(XName.Get("name")).Value
That code is in a foreach over an IEnumerable(of XElement). The stack trace still points to the string assignment, but all other stack traces are spot on, so I don't think it's a bad pdb.
Also, when the error occurred this time, no amount of recycling the app pool or stopping and starting it would fix the error. I finally got it working again by switching the application to a different app pool.

I don't see how that code could throw a null reference exception, are you sure it is not some other code, but the exception message is pointing to the wrong place becuase your pdb files are out of date. The most likely candidate for the code at fault based on your description is some code accessing an application variable that has become null becuase the app pool has recycled due to timeout or because you have republished the web app.

Try declaring the string as a constant... just to zoom in on the issue
Dim Const TESTSTR as String = "test"
Dim teststring As String
teststring = TESTSTR
If that doesn't work, move the Const declaration somewhere global. Maybe it's something to do with how/where .NET stores the string itself becoming invalid.
Try manually recycling the page every time you publish... maybe it's an issue of the pre-compiled code lingering after an update? I admit, that's a head-scratcher, a line like that should never fail.

Related

SQLite issues with finding SQLite.Interop.dll

I'm using SQLite as a means of moving data between a UI and a service but I've run into a few problems. I've looked around and I can't see anyone else with an issue like this. I've triple checked all my references, the x64 folder containing the Interop dll is included in the project, all these dlls are set to copy to the output directory, all directories have the right permissions and nothing's worked.
This is part of a larger problem I'm experiencing where if I use an SQLite Connection in my BackgroundWorker Completed function then the entire service crashes out with File not found exception, if I run an SQLite Connection inside the actual BackgroundWorker I get the Unable to load DLL 'SQLite.Interop.dll' error and finally if I use an SQLite Connection in a function that has no relation to a BackgroundWorker then it works perfectly (referencing this function from either BackgroundWorker event functions results in the same errors respectively).
Any help on this would be great
Code
Dim LiteUpdateString As String = ""
Dim LiteConnection = New SQLiteConnection("Data Source=C:\...\AppData\Roaming\OPCService\Tags.db;Version=3;FailIfMissing=True")
Dim LiteUpdate As String = ""
UpdateNumber += 1
teststring += UpdateNumber.ToString
LiteUpdate = $"UPDATE SQLiteTags SET TagQuality='{teststring}' {SQLWhere}"
Dim Command As New SQLiteCommand(LiteUpdate, LiteConnection)
LiteConnection.Open()
Command.ExecuteReader()
LiteConnection.Close()
Errors
BackgroundWorkerCompleted
Application: OPCService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
at OPCService.OPCService.BackgroundWorker1_RunWorkerCompleted(System.Object, System.ComponentModel.RunWorkerCompletedEventArgs)
at System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(System.ComponentModel.RunWorkerCompletedEventArgs)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
BackgroundWorker
Unable to load DLL 'SQLite.Interop.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I finally managed to find a somewhat workaround, since I can use SQLite in an independent function but can't call that function from a BackgroundWorker event thread, I start a timer once the thread is completed to execute the independent SQLite function.

What could cause GDI+ Initialize exception

I spend a lot of time to search answer but I didn't found it. We have console application (exe) with C1 Report Component for automated printing task. This application is executed from cmd file and cmd file is called by cmdexec from SQL Server 2014 every minute. It's work very fine but there is exceptiton GDI+ Initialize - System.Drawing.SafeNativeMethods+Gdip.Initialize aproximetelly montly. There is no chance to solve this so we must restart server.
I tried to create cmd file with echo command. It was worked fine and I got output from echo. So I created application with Console.Writeline("Hello world") only. It was worked fine. Then I add reference to System.Drawing. Nothing happend - ouput was produced. Then I created System.Drawing.Bitmap object and I got GDI+ Initialize exception.
Job on SQL server run as SQLRUNSERVICES and it is in Administrator group. But when I log as SQLRUNSERVICES and launch our application in command line, application works fine without exception. When I log as another user there is no problem with this. Only with SQLRUNSERVICES throught SQL Proxy.
I suppose there must be something wrong with windows session. This application starts, prints some reports and finishes. So I suppose when application finishes memory will be free and GDI object will be free so. I check if we have call dispose method for each object working with GDI.
Can I have some chance to see GDI objects used by session? Or what could cause this exception? I cannot use task manager because when application is not running there is nothing to see.
Thank you for replies. It is very stresfull problem for us because it is going repeatedly every month after restart server.
We created testing application to print most quickly and we got this exception for one day. We call Dispose method for C1Report ofcourse. We will try to use using section. But it looks like C1 error. Test application printed about 65000 count of document and then crashed by GDI+ Initialization Exception. There is stack:
System.TypeInitializationException: The type initializer for 'Gdip' threw an exception. ---> System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
at System.Drawing.SafeNativeMethods.Gdip.Initialize()
at System.Drawing.SafeNativeMethods.Gdip..cctor()
--- End of inner exception stack trace ---
at System.Drawing.SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(Int32 width, Int32 height, Int32 stride, Int32 format, HandleRef scan0, IntPtr& bitmap)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at C1.C1Preview.GraphicsHolder.FromBitmap()
at C1.C1Preview.GraphicsHolder.FromScreen()
at C1.C1Preview.C1PrintDocument.SelectBestMeasurementDevice(Boolean showWarning, MeasurementDeviceEnum& measurementDevice, String& measurementPrinterName, GraphicsHolder& measurementGraphicsHolder)
at C1.C1Preview.C1PrintDocument.#fFe()
at C1.C1Preview.C1PrintDocument.SetCreationDevice(MeasurementDeviceEnum creationDevice, String creationPrinterName)
at C1.C1Report.Layout..ctor(C1Report report)
at C1.C1Report.C1Report.Initialize()
at C1.C1Report.C1Report..ctor()

Unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

I'm having trouble with this block of code. The StreamWriter creates the .txt document and puts it in the projects bin folder, but when I run the program, I get an error that says:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
the process cannot access the file ... because it is being used by another process.
There are no other programs running on my computer, so I'm not sure what other process could be using it. Here's my code, thanks in advance.
Private Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
Dim voteWriter As IO.StreamWriter
Dim vote As String
voteWriter = IO.File.AppendText("warrenHS.txt")
vote = Convert.ToString(canidateListBox.SelectedItem)
voteWriter.Write(vote)
End Sub
Make sure to close the stream after you are done with it.
voteWriter.Close()
Or you could use it in a using statement that will automatically close it at the end.

The EventLogWebEventProvider provider failed to log an event with the error code 0x80070057

I am writing WebEvent in my asp.net Application and it is working fine in both my development and production region.However, When I analyze Event Logs in production server for past couple of months.I see below event
The following exception was thrown by the web event provider 'EventLogProvider' in the application '/(MyApplicationName)' (in an application lifetime a maximum of one exception will be logged per provider instance):
System.Web.HttpException (0x80004005): The EventLogWebEventProvider provider failed to log an event with the error code 0x80070057.
at System.Web.Management.EventLogWebEventProvider.ProcessEvent(WebBaseEvent eventRaised)
at System.Web.Management.WebBaseEvent.RaiseInternal(WebBaseEvent eventRaised, ArrayList firingRuleInfos, Int32 index0, Int32 index1)
Although Occurrence is very low, still I am curious to understand why this is happening.I tried to do some research and found below link
http://forums.iis.net/t/1201176.aspx?IIS+Keep+hanging
According to this link, I may be passing some invalid argument while writing event log.
But I double checked my EventLog.WriteEntry method and I am using it in my application only in couple of places and moreover, I am passing static string message. If argument is invalid then it should occur every time I try to write event.
Can anyone please help me understanding possible cause for this event.is there any known issue when working with EvenLog?
Check your code you may be trying to perform an invalid operation.
In my case i was writing a file to C Drive after changing Location to D Drive Problem Resolved

Rare System.NullReferenceException show up for a HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"] that was previously populated?

Our ASP.NET C# web application is used in the following environment
.NET Framework 4
Silverlight 4 / PivotViewer
IIS 7
Windows 2008
Visual Studio 2010 .NET IDE
C#
HTTPS ( SSL )
Our Silverlight 4 / PivotViewer controls are obviously embedded in
ASP.NET pages.
In rare cases we get the "Object reference not set to an instance of
an object. error when navigating around ASP.NET pages that host our
Silverlight 4 / PivotViewer modules on our standalone Windows 2008
server with IIS 7.
Also, there is number of very odd things about the error. First, it
occurs only sometimes on certain user computers. To elaborate, it
usually only occurs when a the user uses a computer that accesses our ASP.NET web application for the first time.
Moreover, once we clear the browser cache the error does Not occur
when navigating around ASP.NET pages that host our
Silverlight 4 / PivotViewer modules.
Another interesting aspect about the error is that it refers to
absolute path on my local development computer in the error stack
trace when it is in reality deployed to the standalone Windows 2008
server with IIS 7. That`s really strange because before I deploy to
the standalone Windows 2008 server with IIS 7, I ensure that all
configuration parameters in files such as web.config refer to the
standalone server environment. In other words, I remove any
references to configuration parameter values associated with my local
development computer.
Therefore, I am confused as to why it refers to absolute path on my
local development computer in the error stack trace.
It would be bad experience for the user to get the "Object reference
not set to an instance of an object.` while using the site. Also, it
would be bad user experience if we have to tell the user to clear
his/her browser cache everytime the error shows up.
Server Error in '/' Application.
Object reference not set to an instance of an object.
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.]
PivotServer.SectionBasedRelatedModules.SectionBasedPerlsViewer.tailorConfigurationDetailsOfPageElementsToFallInLineWithTutorialSelection()
in C:\VisualStudioWorkSpace\VisualCSharpProjects\PerlsPivot\PivotServer\SectionBasedRelatedModules\SectionBasedPerlsViewer.aspx.cs:160
PivotServer.SectionBasedRelatedModules.SectionBasedPerlsViewer.Page_Load(Object
sender, EventArgs e) in
C:\VisualStudioWorkSpace\VisualCSharpProjects\PerlsPivot\PivotServer\SectionBasedRelatedModules\SectionBasedPerlsViewer.aspx.cs:146
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)
+3063
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.272
I looked at line 160 which contains the following code:
String coursename = HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"].ToString();
Obviously, this tells us that there is no value for the variable "courseNameAssociatedWithLoggedInUser" in the HttpContext.Current.Session.
However, I took the same steps on another computer but it all ran smoothly.
Also, I am sure that I am giving a value to the HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"] as soon as the user logs in.
Does the HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"] get corrupted for some reason? If so, why, and how do we prevent it?
Should I be using Page.Session instead of HttpContext.Current.Session? Would that help?
"Obviously, this tells us that there is no value for the variable"courseNameAssociatedWithLoggedInUser" in the
HttpContext.Current.Session."
Not exactly... given your code...
String coursename = HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"].ToString();
... the following items could be causing this
HttpContext - unlikely
HttpContext.Current - more often than you would think, but would be reproducible
HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"]
To find out the specific item in that chain, you could do something like this (pseudo code)
function string GetCourseNameThingie()
{
if HttpContext is null
throw new Exception("HttpContext is null")
if HttpContext.Current is null
throw new Exception("HttpContext.Current is null")
if HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"] is null
throw new Exception("HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"]is null")
return HttpContext.Current.Session["courseNameAssociatedWithLoggedInUser"].ToString()
}
This would tell you specifically what was missing. As we have pointed out, it is more likely the value is either being cleared by another page or an error is occurring that is severe enough to destroy session for that user (Do you have a Application_Error or Session_End handler in Global.asax?).
You can also try wrapping the original statement in a try/catch and if an exception occurs, immediately check another session variable you assume to be still working. This will also tell you for sure whether the other variables are OK or not.
First, sorry for my grammar-English.
I had a similar issue with my .net applications and the reason was the idle time expiration.
There are four time expiration settings "(Yes 4)" and the recycling process of the application pools. I did the following
A) From Application pool: Open the advance setting and change the "Idle Time out". By default is 20 minutes.
Also, set the "Regular Time Interval" to 0. so it wont be recycled. I do not know why microsoft decided to default this to 1740 minutes. This is not a time out setting, it is a setting for always recycling the appPool after a period of time, so if your users are in the middle of something they will loose everything or having exceptions like that one you are having. Setting it to 0 will disable this.
B) Authentication Time Out. if you are using it, for example Form Authentication, then go to the authentication feature of your virtual directory app, right click in "Form Authentication" and select "Edit". Change the authentication cookie-time out.
C) ASP.NET Session State. in ISS, open the .net session state feature and change the session time-out. It is also by default 20 minutes.
D) asp.net form authentication time out. This was confusing for me at the beginning because I had already modified the cookie-time out of the form authentication in IIS (Step B). So I still had some problems, when I realised that I also need to change the web.config form authentication tag in order to add a time out attribute for changing the default 20 minutes.
My tag is looking like that: ...forms name=".ASPXFORMSAUTH" path="/" loginUrl="frmLogin.aspx" timeout="1740" protection="All" ...
We have developed a javascript mechanism that take the session state time out setting so we warm users that the system is about to auto log off due to inactivity.
It works beautiful now, Basically I have set all the time out settings to "1740" minutes, except the session state that we set to 30 minutes. So at the minute 29 of inactivity we show the user that the system will auto log off in a minute unless that they do some activity so the idle time is beginning from 0 again. Brilliant, now we do not have any problem with sessions.
Anyway guys, I have told you our experience and how we solve a similar problem that you are having now. However, the reason why I ended here is because we also want to eliminate the references to the absolute path on my local development computer at the moment of any exception.
We have not figured out why it is showing the absolute path. We have compiled our DLL assemblies in released mode, but this does not change anything. Have someone of you sort it out this issue?????
Thanks guys
Referencing a Session Within a ViewModel
You may not be using ASP.net MVC, but this would be useful if someone were to be looking for an answer.
I was in exactly the same situation except I would receive the null exception every time, whereas my colleague didn't at all, even though we were running exactly the same code.
Our mistake was to reference a session variable from a ViewModel, which is apparently bad practice. The code was changed so that the ViewModel received the session contents via the controller then set it as a property of the ViewModel. The session data (my example is called ProcessingWeek) would use this.ProcessingWeek, and not look directly at the httpcontext.current.session["ProcessingWeek"].
EventMatchResult Match = new EventMatchResult(
(ImportedEventModel)SessionData.ImportedEventModel,
ref db,
SessionData.ProcessingWeek);
...
public EventMatchResult(ImportedEventModel Event, ref CFModel db,
int ProcessingWeek)
{
this.db = db;
this.MatchedField = new List<PlayerMatchResult>();
this.ImportedEvent = Event;
this.ProcessingWeek = ProcessingWeek;
}

Resources