Once in every few hundred times I get an error on the life site 'bout losing the object.
I've been checking and testing and testing but have not got a clue what's goin' wrong.
Anyone some bright idea?
The code is:
Dim MySqlCommand = New MySqlCommand(SQLC, MySqlConnect)
Try
Tries = 5
lg &= " Co("
Do
Try : MySqlCommand.Connection.Open()
Catch ex As Exception
lg &= " " & ex.Message
Wait(0.5)
End Try
If (MySqlCommand.Connection.State <> ConnectionState.Open) Then Tries -= 1
Loop While Tries > 0 And MySqlCommand.Connection.State <> ConnectionState.Open
lg &= ")"
Catch ex As Exception
lg &= ex.message
End Try
lg &= " " & LCase(Left(SQLC, 5)) & "(Mc"
Try
lg &= "En" : Dim ret = MySqlCommand.ExecuteNonQuery()
lg = ""
Catch ex As Exception
lg &= ":" & ex.message
End Try
if lg<>"" then Response.write(lg)
The Output is:
Co() updat(McEn:Object reference not set to an instance of an object.
Use a .net logging framework, like log4net. Log what is happening on your page.
In my experience, logging is the best way to catch intermittent bugs.
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
My code updates & inserts into a bunch of tables. About 2 months ago I got the same error as the one below, I assumed it was because the exception it self is Nothing.
So I built in a test to check if it isn't nothing, write the exception details.
However, the error in the screenshot occurred again this morning. My question now is how does a code block like the one below result in the Exception being Null, and in which cases will an exception be Null?
Edited - This is different to this question because I want to know how an EXCEPTION can be Null/Nothing
Try
If t.DpaPosted = "N" Then
i += 1
OutputCount += 1
Dim SubAccountID As Integer = 0
If t.SubaccountId = 0 Then
SubAccountID = GetSubAccountID(t.DpaInId)
If SubAccountID = 0 Then
If DupAcc > 1 Then
UpdateLog(t.clientReference & " - Multiple CLOSED(Paid Up/Refunds outstanding) accounts.")
Else
SubAccountID = GetClosedSubAccountID(t.DpaInID)
If SubAccountID = 0 Then
UpdateLog(t.clientReference & " - No accounts found.")
End If
End If
End If
End If
If SubAccountID <> 0 Then
If t.DpaDocNo <> "0" Then
If q.Execquery("SELECT COUNT(1) FROM Transactions WHERE SubAccountID = " & t.SubaccountId & " AND TranTypeID = 6 AND TranAmount = " & t.DpaAmount & " AND DPANo = '" & t.DpaDocNo & "'") > 0 Then
HttpContext.Current.Response.Write("Sequence [" & t.DpaDocNo & "] already posted.<br/>")
dpaadapter.SetDpaPosted(t.DpaInId)
Else
PostDpa(SubAccountID, 6, t.DpaAmount, t.Dpadate, "0", t.DpaDocNo)
dpaadapter.SetDpaPosted(t.DpaInId)
End If
Else
PostDpa(SubAccountID, 6, t.DpaAmount, t.Dpadate, "0", t.DpaDocNo)
dpaadapter.SetDpaPosted(t.DpaInId)
End If
End If
If WriteOutput Then HttpContext.Current.Response.Write("Imported [" + i.ToString + "] of [" + dpa.Rows.Count.ToString + "]<br/>")
If OutputCount = 10 Then
OutputCount = 0
If WriteOutput Then
If HttpContext.Current.Response.IsClientConnected Then
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Write("<script>window.scrollTo(0,document.body.scrollHeight);</script>")
HttpContext.Current.Response.Flush()
End If
End If
End If
End If
Catch ex As Exception
Dim LogStr As String = ""
LogStr = "Record [" & i.ToString & "]. "
LogStr = "Ref [" & t.clientReference & "] - "
If ex.Message.ToString <> Nothing Then LogStr = LogStr & ex.Message.ToString Else LogStr = LogStr & "No Exception Message"
If ex.InnerException.ToString <> Nothing Then LogStr = LogStr & vbCrLf & ex.InnerException.ToString Else LogStr = LogStr & "No Inner Exception"
UpdateLog(LogStr)
SaveLog()
End Try
I can't actually see what code is triggering the exception, until I can fix the exception handling.
Some more information that might help
I am using asp.net V 4.0
The code is in a class, and the file is located in the appcode directory.
The issue doesn't always trigger
When running the code for a second/third time, the exception doesn't trigger again. So I can't recreate the error all the time.
Windows event viewer didn't log any exceptions for this page.
ANSWER
Found from this question.
An inner exception is the exception that caused the current exception.
It is used in cases when you want to surface a different exception
than the one that your code caught but you don't want to throw away
the original context.
In order for a new exception to have information about a previous one,
like you said, you pass it as constructor parameter to the new one.
Usually, a null inner exception means that the current exception is
root cause of the exceptional situation.
How about safeguarding your ex.InnerException? Once you make sure that an InnerException exists then you can access its methods and properties.
If ex.InnerException Is Not Nothing AndAlso ... Then
See this explanation (and read the accepted answer) about InnerException. It is not necessary to have an InnerException, unless the current exception was caused by another exception.
I am running Windows 7 Professional. I have an MS Access frontend to an MS Access backend. The form that opens at the start of opening the frontend causes the app to crash.
Here is the code:
Private Sub Form_Open(Cancel As Integer)
Dim strMyDir As String
Dim intPos As Integer
Dim rst As dao.Recordset
Dim strSQL As String
Dim rstWhatsNew As dao.Recordset
DoCmd.ShowToolbar "Database", acToolbarNo
DoCmd.ShowToolbar "Toolbox", acToolbarNo
DoCmd.ShowToolbar "Form View", acToolbarNo
If Application.GetOption("ShowWindowsInTaskbar") = -1 Then
Application.SetOption "ShowWindowsInTaskbar", 0
End If
If DLookup("Locked", "luLockOut") <> 0 Then
MsgBox "Database is being worked on. Please try back in a couple minutes.", vbInformation, " "
DoCmd.Quit
Else
strSQL = "Select * From tblLastLogins Where UserName = '" & GetCurrentUserName() & "'"
This is where I have traced the error to: GetCurrentUserName()
Set rst = CurrentDb.OpenRecordset(strSQL)
With rst
If Not .EOF Then
.Edit
strSQL = "Select WhatsNewID From tblWhatsNew Where DateAdded >= #" & !LastLoginDate & "#"
Set rstWhatsNew = CurrentDb.OpenRecordset(strSQL)
While Not rstWhatsNew.EOF
DoCmd.OpenForm "frmWhatsNew", , , , , acDialog, rstWhatsNew!WhatsNewID
rstWhatsNew.MoveNext
Wend
rstWhatsNew.Close
Set rstWhatsNew = Nothing
Else
.AddNew
!UserName = GetCurrentUserName()
End If
!LastLoginDate = Now()
!IsLoggedIn = -1
Me.txtLastLoginID = !LastLoginID
.Update
.Close
End With
Set rst = Nothing
DoCmd.OpenForm "frmPrivacyNote"
Debug.Print Me.txtLastLoginID
End If
I need to track the username, so if GetCurrentUserName() is outdated, what is the current syntax?
Further follow up. I could not find data on Bing for GetCurrentUserName(), for good reason. It is a function within a MOD, so I need to figure out why the MOD is not getting called, or is malfunctioning.
After further delving, I found a Referenced MDB that has another function created by one of our users that is the cause of this error.
This is currently not an issue of MS Access working incorrectly. It is an issue with user created code.
GetCurrentUserName() is not defined by Access, so you should have looked at (and posted) its code.
If you are looking for the Windows user name, use this function:
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Environ("USERNAME") is easily spoofed, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
Source
The link below would suggest that
CurrentUser()
is the function
CurrentUser()
Andre, thank you very much for the insight! I found this link:
http://www.codeproject.com/Articles/1422/Getting-User-Information-Using-WSH-and-VBScript
Dim objNet
On Error Resume Next
'In case we fail to create object then display our custom error
Set objNet = CreateObject("WScript.NetWork")
If Err.Number <> 0 Then 'If error occured then display notice
MsgBox "Don't be Shy." & vbCRLF &_
"Do not press ""No"" If your browser warns you."
Document.Location = "UserInfo.html"
'Place the Name of the document.
'It will display again
End If
Dim strInfo
strInfo = "User Name is " & objNet.UserName & vbCrLf & _
"Computer Name is " & objNet.ComputerName & vbCrLf & _
"Domain Name is " & objNet.UserDomain
MsgBox strInfo
Set objNet = Nothing 'Destroy the Object to free the Memory
It might be a little funny but I am facing some stupid issue.
I am using
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
and
Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
when I using this the error is given to me is "Could not find a part of the path "
If am storing the path in a string then its working fine else producing error.
For your reference I am copying my function code snippet.
Please help
Thanks
Public Shared Function LogErrorToLogFile(ByVal ee As Exception, ByVal userFriendlyError As String) As String
Try
Dim path As String = context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))
' check if directory exists
If Not Directory.Exists(path) Then
'Directory.CreateDirectory(path)
Directory.CreateDirectory(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
End If
path = path & DateTime.Today.ToString("dd-MMM-yy") & ".log"
' check if file exist
If Not File.Exists(path) Then
File.Create(path).Dispose()
'File.Create(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))).Dispose()
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
End If
' log the error now
Using writer As StreamWriter = File.AppendText(path)
'Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
writer.WriteLine(HttpUtility.HtmlEncode(vbCr & vbLf & "Log written at : " & DateTime.Now.ToString() & vbCr & vbLf & "Error occured on page : " & context.Current.Request.Url.ToString() & vbCr & vbLf & vbCr & vbLf & "Here is the actual error :" & vbLf & ee.ToString()))
writer.WriteLine("==========================================")
writer.Flush()
writer.Close()
End Using
Return userFriendlyError
Catch
Throw
End Try
End Function
If you change the current lines with the comment-outed lines in your function code snippet, you're logic is changed because when you use Path, there is added a filename [dd-MMM-yy].log to the path-string. but you don't use that addition when you use the ConfigurationManager.AppSettings("LogFilePath1") directly!
I assume that you have not used the folder path with slash (ex: #"C:\FolderName\") and that is the reason you are getting the error.
I have an error handler in my global.asax as follows;
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim ex = Server.GetLastError.GetBaseException
Dim lastErrorWrapper As HttpException = Server.GetLastError()
Dim lastError As Exception = lastErrorWrapper
If lastErrorWrapper.InnerException IsNot Nothing Then
lastError = lastErrorWrapper.InnerException
End If
My.ErrorHandler.LogError( _
"<BR/><BR/>URL: " & Request.RawUrl & _
"<BR/><BR/>STACK: " & ex.StackTrace & _
"<BR/><BR/>SOURCE: " & ex.Source & _
"<BR/><BR/>MESSAGE: " & ex.Message & _
"<BR/><BR/>TYPENAME: " & ex.GetType.ToString & _
"<BR/><BR/>INNER EXCEPTION: " & lastError.ToString & _
"<BR/><BR/>REFERRER: " & HttpContext.Current.Request.Url.AbsoluteUri & _
"<BR/><BR/>USER IP: " & Request.ServerVariables("REMOTE_ADDR") & " -- " & Request.ServerVariables("HTTP_USER_AGENT"))
End Sub
Obviously, this works great and sends me an email whenever there is an error. But, this is also true for any images that are not found in the file system. It gives me a "File does not exist." error. Is there a way to ignore logging errors for images that are not located on disk?
Cant you resolve the FileNotFoundException instead? If the exception should not occur then rather resolve the issue than suppressing it. To handle a known exception you can use the following code.
if(Server.GetLastError().GetBaseException() is System.Web.HttpException)
{
//You could check whether the
//Server.GetLastError().GetBaseException().Message contains the appropriate message
Debug.WriteLine("Suppressed FileNotFoundException");
}else
//Log an unhandled exception
var ex = Context.Error;
if (ex is HttpException)
{
var httpException = (HttpException)ex;
if (httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
return; // Do nothing 404
}
I know that this sounds very easy, or very simple, or you may search for the error code, but this is what I do - simple check if the error contains the message of dose not exist:
lastErrorWrapper.ToString().Contains("does not exist.")
For a web application, I am creating a SMS module that can send an SMS from the application. My SMS provider has an API that I can call over HTTP.
The API is called via an XmlTextReader who just reads the XML response from the API.
Now my problem is: When I send the SMS from a web page (basically just doing an HTTP request) it takes more than a minute before I receive the SMS.
But when I run the exact same code from a Windows console application, my SMS arrives in less then 5 seconds.
I have done multiple tests with this, and it's not really my SMS provider who is slow.
Somehow, the HTTP request gets delayed from within the ASP.NET engine, and it does not delay directly from an console application. Is there a solution?
This is the way I'm calling the HTTP API:
Dim strPostString As String = Convert.ToString(muriPostUrl) & mstrPostPath
If mblnUseSecureConnection Then
strPostString = Convert.ToString(muriSecurePostUrl) & mstrPostPath
End If
Dim strDataString As String = "username=" & mstrUsername
strDataString += "&" & "password=" & mstrPassword
strDataString += "&" & "originator=" & mstrOriginator
strDataString += "&" & "recipients=" & mstrRecipients
strDataString += "&" & "gateway=" & mstrGateway
strDataString += "&" & "reference=" & mstrReference
strDataString += "&" & "message=" & mstrMessage
If mstrType <> String.Empty Then
strDataString += "&" & "type=" & mstrType
End If
If mstrUDH <> String.Empty Then
strDataString += "&" & "udh=" & mstrUDH
End If
If Not mdtDeliveryDate = Nothing Then
Dim objDeliveryDate As New StringBuilder()
objDeliveryDate.Append(mdtDeliveryDate.Year)
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Month.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Day.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Hour.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Minute.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Second.ToString(), 2))
strDataString += "&" & "deliverydate=" & Convert.ToString(objDeliveryDate)
End If
Dim strReturnValue As String = ""
Dim xmlReader As New XmlTextReader(String.Format("{0}?{1}", strPostString, strDataString))
While xmlReader.Read()
If xmlReader.NodeType = XmlNodeType.Element Then
Select Case xmlReader.LocalName
Case "recipients"
If True Then
mintSuccessCount = Integer.Parse(xmlReader.ReadString())
strReturnValue += "recipients : " & mintSuccessCount.ToString() & vbCr & vbLf
Exit Select
End If
Case "success"
If True Then
mblnSuccess = Boolean.Parse(xmlReader.ReadString())
strReturnValue += "success : " & mblnSuccess.ToString() & vbCr & vbLf
Exit Select
End If
Case "resultcode"
If True Then
mintResultCode = Integer.Parse(xmlReader.ReadString())
strReturnValue += "resultcode : " & mintResultCode.ToString() & vbCr & vbLf
Exit Select
End If
Case "resultmessage"
If True Then
mstrResultMessage = xmlReader.ReadString()
strReturnValue += "resultmessage : " & mstrResultMessage & vbCr & vbLf
Exit Select
End If
End Select
End If
End While
Also, when performing an HTTP request from ASP.NET, it does not appear in Fiddler, while the actual HTTP request happens. How can I track the HTTP fastback from within the ASP.NET engine?
I still don't know what the problem is, but I worked around it by doing the postback via an HttpWebRequest directly. I think the problem was somewhere in the while loop.