This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
Hello everyone I've been struggling with this error message for days:
Here is the error message:
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:
Line 7:
Line 8: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Line 9: UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
Line 10: cannotUploadImageMessage.Visible = False
Line 11: End Sub
Source File: C:\Users\Collins\Documents\Visual Studio 2005\WebSites\living to please god world\PhotoAdmin\Default.aspx.vb Line: 9
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
PhotoAdmin_Default.Page_Load(Object sender, EventArgs e) in C:\Users\Collins\Documents\Visual Studio 2005\WebSites\living to please god world\PhotoAdmin\Default.aspx.vb:9
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
This is my complete code to upload photos. Can someone help me please?
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class PhotoAdmin_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
cannotUploadImageMessage.Visible = False
End Sub
Protected Sub dvPictureInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvPictureInsert.ItemInserted
'If the record was successfully inserted, save the picture
If e.AffectedRows > 0 Then
'Determine the maximum pictureID for this user
Dim results As DataView = CType(maxPictureIDDataSource.Select(DataSourceSelectArguments.Empty), DataView)
Dim pictureIDJustAdded As Integer = CType(results(0)(0), Integer)
'Reference the FileUpload control
Dim imageUpload As FileUpload = CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If imageUpload.HasFile Then
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
imageUpload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
End If
End If
If e.Exception Is Nothing Then
' Use the AffectedRows property to determine whether the
' record was inserted. Sometimes an error might occur that
' does not raise an exception, but prevents the insert
' operation from completing.
If e.AffectedRows = 1 Then
MessageLabel.Text = "Record inserted successfully."
Else
MessageLabel.Text = "An error occurred during the insert operation."
' Use the KeepInInsertMode property to remain in insert mode
' when an error occurs during the insert operation.
e.KeepInInsertMode = True
End If
Else
' Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception has already been handled.
e.ExceptionHandled = True
e.KeepInInsertMode = True
End If
End Sub
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Dim acceptedExtensions = New String() {".jpg", ".png", ".gif"}
If Not acceptedExtensions.Contains(imageUpload.FileName, StringComparer.OrdinalIgnoreCase) Then
cancelInsert = True 'Invalid image file!
End If
Else
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream)
If image.Width > 1300 Or image.Height > 950 Then
cancelInsert = True
End If
End If
If cancelInsert Then
e.Cancel = True
cannotUploadImageMessage.Visible = True
End If
'Set the UserId value to the currently logged on user's ID
e.Values("UserId") = Membership.GetUser().ProviderUserKey
'Set the UploadedOn value to the current date/time
e.Values("UploadedOn") = DateTime.Now
End Sub
Protected Sub gvPictures_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvPictures.RowDeleted
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
Dim fileName As String = baseDirectory & e.Keys("PictureID") & ".jpg"
File.Delete(fileName)
End Sub
Protected Sub gvPictures_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvPictures.RowUpdating
e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
End Sub
End Class
Are you sure Membership.GetUser() is actually returning a user?
You are authenticated and not an anonymous user, correct? You should add a null check or a check to make sure they are authenticated first. I believe you can use User.Identity.IsAuthenticated
Just while editing for formatting I see line 9 has to do with membership and a control. Gut instinct is saying you're not logged in or that control doesn't exist.
Place a breakpoint at your line 9, run the site in debug, and see if the Membership.GetUser() or UserIdValue are null.
Related
I want to pass the exception Url as a string to a method that I have created , so that it shows the exception Url in the mail (that is sent).
I have done the following in my ApplicationError() event in my Global.asax
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim lastException As Exception = Server.GetLastError()
If (lastException Is Nothing) Then
Return
End If
Dim context As HttpContext = HttpContext.Current
Dim myMethodforMail As New myMethodforMail()
Dim exUrl As String = context.Request.Url.ToString()
Dim webServerName As String = Server.MachineName
myMethodforMail.HandleApplicationError(exUrl, webServerName)
Server.ClearError()
End Sub
But the url is printed as http://localhost:22035/examplepage.aspx?PageNumber!0331
instead of http://localhost:22035/examplepage.aspx?PageNumber=650331
could anyone kindly help me how to decode the ! in the Url and represent the Url as it is, please . ThankYou.
I'm working on a Login session through Visual Basic with asp.net. When the session timeout is complete and I click on another different page it gives me an error, "Object reference not set to an instance of an object." SessionState mode="InProc"
Here is the code that I used for the session:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("Username") Is Nothing Then
Label1.Text = "Welcome, " & Session("Username").ToString()
End If
End Sub
If Session("Username") IsNot Nothing Then
Label1.Text = "Welcome, " & Session("Username").ToString()
Else
Response.Redirect("~/Default.aspx")
End If
You need to check for if it's not null before you reference it. You were doing the opposite. You were checking to see if it's null, verifying it was, then referencing it. That's why you get a NullReferenceException. Basically all null reference exceptions are the same, you're trying to perform an operation on an object that is null.
Use a built in function which is exactly what you are looking for :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsNothing(Session("Username")) Then
Label1.Text = "Welcome, " & Session("Username").ToString()
End If
End Sub
That's all :=)
Cheers
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
i am experiencing thi error when i click on the application in the remote machine.
Server Error in '/please-god' Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
Line 7: Dim oBF As New BinaryFormatter()
Line 8: Dim oFS As FileStream
Line 9: Dim strPath As String = Path.GetTempPath & "schedule.Bin"
Line 10:
Line 11: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Source File: D:\Hosting\4423045\html\please-god\appointmentscheduler.aspx.vb Line: 9
Can someone help me? the full codes for the application is this :
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Partial Class appointmentscheduler
Inherits System.Web.UI.Page
Dim arrCalendar(12, 31) As String
Dim oBF As New BinaryFormatter()
Dim oFS As FileStream
Dim strPath As String = Path.GetTempPath & "schedule.Bin"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Cache("arrCalendar") Is Nothing) Then
If (File.Exists(strPath)) Then
oFS = New FileStream(strPath, FileMode.Open)
arrCalendar = DirectCast(oBF.Deserialize(oFS), Array)
oFS.Close()
Cache("arrCalendar") = arrCalendar
End If
Else
arrCalendar = Cache("arrCalendar")
End If
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day) = Me.myNotes.Text
oFS = New FileStream(strPath, FileMode.Create)
oBF.Serialize(oFS, arrCalendar)
oFS.Close()
Cache("arrCalendar") = arrCalendar
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day) = ""
oFS = New FileStream(strPath, FileMode.Create)
oBF.Serialize(oFS, arrCalendar)
oFS.Close()
Cache("arrCalendar") = arrCalendar
Me.myNotes.Text = ""
End Sub
Protected Sub myCalendar_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles myCalendar.DayRender
If arrCalendar(e.Day.Date.Month, e.Day.Date.Day) <> "" Then
e.Cell.BackColor = Drawing.Color.Red
End If
End Sub
Protected Sub myCalendar_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myCalendar.SelectionChanged
Me.myNotes.Text = ""
If arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day) <> "" Then
Me.myNotes.Text = arrCalendar(Me.myCalendar.SelectedDate.Month, Me.myCalendar.SelectedDate.Day)
End If
End Sub
End Class
What do i have to do to eliminate this error message?
It looks like you're attempting to open a file that is outside of the web application's root directory. Either move the file into a place where the service account used by IIS has permission to read the file or change the read/write permissions on the file you're attempting to read.
Did you type the error message by hand? Path.GetTempPath is a method and should cause a compile error if you don't use the syntax Path.GetTempPath(). Makes it hard to dig too deeply into the error messages you've posted if they may not be correct.
I was doing a test to upload pictures and i found out that when i upload pictures more than 2000px the webpage turn to be slow. I want users to upload pics with size not more than 600px and height 700px.
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class PhotoAdmin_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
cannotUploadImageMessage.Visible = False
End Sub
Protected Sub dvPictureInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvPictureInsert.ItemInserted
'If the record was successfully inserted, save the picture
If e.AffectedRows > 0 Then
'Determine the maximum pictureID for this user
Dim results As DataView =
CType(maxPictureIDDataSource.Select(DataSourceSelectArguments.Empty),
DataView)
Dim pictureIDJustAdded As Integer = CType(results(0)(0), Integer)
'Reference the FileUpload control
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If imageUpload.HasFile Then
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
imageUpload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
End If
End If
If e.Exception Is Nothing Then
' Use the AffectedRows property to determine whether the
' record was inserted. Sometimes an error might occur that
' does not raise an exception, but prevents the insert
' operation from completing.
If e.AffectedRows = 1 Then
MessageLabel.Text = "Record inserted successfully."
Else
MessageLabel.Text = "An error occurred during the insert operation."
' Use the KeepInInsertMode property to remain in insert mode
' when an error occurs during the insert operation.
e.KeepInInsertMode = True
End If
Else
' Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception has already been handled.
e.ExceptionHandled = True
e.KeepInInsertMode = True
End If
End Sub
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Else
If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then
cancelInsert = True 'Invalid image file!
End If
End If
If cancelInsert Then
e.Cancel = True
cannotUploadImageMessage.Visible = True
End If
'Set the UserId value to the currently logged on user's ID
e.Values("UserId") = Membership.GetUser().ProviderUserKey
'Set the UploadedOn value to the current date/time
e.Values("UploadedOn") = DateTime.Now
End Sub
Protected Sub gvPictures_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvPictures.RowDeleted
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
Dim fileName As String = baseDirectory &
e.Keys("PictureID") & ".jpg"
File.Delete(fileName)
End Sub
Protected Sub gvPictures_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvPictures.RowUpdating
e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
End Sub
End Class
Setting a max width and height on an uploaded image isn't necessarily going to fix your problem as you could upload an image with a much higher DPI and it still be a "large" image with small dimensions. Also, you would have to check the image dimensions once the image had been uploaded to your server.
You could set a maxiumum file size in the web.config using the maxRequestLength property which could be used to prevent a large file being uploaded...
Sorry if my vb is wrong as im a c# guy!! but I hope this should give you a guidance. I do something similar in c#. Good luck
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Else
If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then
cancelInsert = True 'Invalid image file!
Else
Dim image As System.Drawing.Image =
System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream)
If image.Width > 600 Or image.Height > 700 Then
cancelInsert = True
End If
End If
End If
//etc