System.Web.Services.Protocols.SoapException - vb.net

This error is generated in a ratio of 5:1. 4 times it will work without error, but the next time it runs it will return the error "Object reference not set to an instance of an object" for the same query string.
My system uses a web service (SVC) to connect to a MySql database for all of its CRUD operations. The Error is listed below:
System.Web.Services.Protocols.SoapException: DELETE FROM
customer_number WHERE cus_id =4 Object reference not set to an
instance of an object. at
System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
message, WebResponse response, Stream responseStream, Boolean
asyncCall) at
System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
methodName, Object[] parameters) at
POS.ThePOSServerService.PosMain.ExecuteQueryBool(String strQuery,
String Company, String User, String Pass) in Reference.vb:line 266
While the code that generates error is as follows with line numbers:
Try
261 Dim ConnectionString As String = _
ConfigurationManager.ConnectionStrings(Company).ConnectionString
262 'Dim sCommand As StringBuilder = New 262 - StringBuilder(strQuery)
263 Using mConnection As MySqlConnection = New MySqlConnection(ConnectionString)
264 mConnection.Open()
265 Using myCmd As MySqlCommand = New MySqlCommand(strQuery, mConnection)
266 myCmd.CommandType = CommandType.Text
267 Result = myCmd.ExecuteNonQuery() > 0
268 End Using
269 End Using
Catch ex As Exception
Throw New ApplicationException(ex.ToString)
End Try
I just want to get Result to be True or False to return as a value.

It is my fault. never checked that the connection string was correctly coming into the function. once I corrected that (giving the correct connection string) everything went as I was expecting. Thanks to all anyway.

Related

Is this err caused by trying to process too many controls on the web form?

I get this err page:
Server Error in '/EMS/customerreportingnet' Application.
Operation is not valid due to the current state of the 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.InvalidOperationException: Operation is not valid due to the current state of the 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:
[InvalidOperationException: Operation is not valid due to the current state of the object.]
System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +4198079
System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) +60
System.Web.HttpRequest.FillInFormCollection() +189
[HttpException (0x80004005): The URL-encoded form data is not valid.]
System.Web.HttpRequest.FillInFormCollection() +11196408
System.Web.HttpRequest.get_Form() +119
System.Web.TraceContext.InitRequest() +1188
System.Web.TraceContext.VerifyStart() +133 System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +11307449
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +452
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491
...when I click the button which fires this code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Exploding' WHERE Unit = #Unit And MemberNo = #MemberNo AND Custno = #CustNo"
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
Dim curIndexVal As String
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is CheckBox Then
If DirectCast(cntrl, CheckBox).Checked = True Then
curIndexVal = DirectCast(cntrl, CheckBox).ID
coName = GetLabelTextForID(curIndexVal)
argVals = GetArgValsForCompanyName(coName)
_Unit = argVals(0)
_MemberNo = argVals(1)
_CustNo = argVals(2)
Using conn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#CustNo", SqlDbType.VarChar, 50).Value = _CustNo
conn.Open
cmd.ExecuteScalar()
End Using
End If
End If
Next
End Sub
My guess is that this is because the literally thousands of label/checkbox pairs of controls on the form are too much to handle (no pun intended). If this reckoning is right, what is the limit of controls that the page will host without whin[g]ing?
Is there a workaround where I can deal with thousands of label/checkbox pairs?
Or is it the number of update statements that are causing the problem?
The err msg seems to indicate too many controls to deal with...

String is not assigned in a while loop

I'm reading a file from a FTP server, and I'm trying to use a while loop to assign the next line to a String and check if it's not null (Nothing).
The issue is that I'm pretty much used to C#, and this is my first attempt at VB. Can you tell me if I did something wrong that's causing it?
Dim request As WebClient = New WebClient()
Dim url As String = "ftp://ftp.harelwebs.net/" + "Default.aspx"
request.Credentials = New NetworkCredential("USERNAME", "PASS")
Try
Dim stream As IO.Stream = request.OpenRead(url)
Dim sr As StreamReader = New StreamReader(stream)
Dim line As String = Nothing
While (stream.CanRead And (line = sr.ReadLine()) <> Nothing)
MessageBox.Show(line)
End While
stream.Close()
sr.Close()
Catch ex As WebException
MessageBox.Show("Error.. " + ex.Message)
I've tested the same code in C# and it works perfectly, I have no idea why it doesn't work in VB.
Unfortunately you cannot assign a value in VB.NET inside a test clause. The reason being that = is used for both assignment and comparison and it would be very confusing and ambiguous in cases.
The solution to your problem would simply be to do this:
Dim line As String = sr.ReadLine()
While (stream.CanRead And line <> Nothing)
MessageBox.Show(line)
line = sr.ReadLine()
End While
If necessary you could wrap the assignment in an if statement if there may be instances where you want to set the line value to Nothing to prevent the loop running.

Web request not repeating after failure, try/catch not working

I am trying to send a web request to a Snom PA1 bell. The bell rings periodically throughout the day, but occasionally times out trying to contact the bell. That would be fine, but after this happens a couple times, the web request stops sending altogether. the sub still runs, but no bells. Also, while debugging, the webrequest throws a webexception that is not handled by the catch, even though it is contained within the try/catch.
Does anyone know why the web request would stop working after a failure?
Private Sub ringIPBell(ByVal params() As Object, Optional ByVal secondattempt As Boolean = False)
Dim IPaddress As String = params(0)
Dim ringSeconds As Double = params(1)
Dim wr As Net.HttpWebRequest
If ringSeconds = 2 Then
wr = Net.HttpWebRequest.Create("http://" & IPaddress & "/line_login.htm?l=2")
Else
wr = Net.HttpWebRequest.Create("http://" & IPaddress & "/line_login.htm?l=1")
End If
wr.Method = "post"
wr.CachePolicy = New System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore) 'added Oct2010
wr.Credentials = New Net.NetworkCredential("correctName", "correctPassword")
Dim postdata As String = "PLAY_RINGER:1=Play Ringer"
wr.ContentLength = postdata.Length + 2
Dim requestStream As IO.Stream, strmwrit As IO.StreamWriter
Try
requestStream = wr.GetRequestStream()
strmwrit = New IO.StreamWriter(requestStream)
strmwrit.WriteLine(postdata)
strmwrit.Close()
Dim responsestream As New IO.StreamReader(wr.GetResponse.GetResponseStream)
Catch ex As System.Net.WebException
If Not secondattempt Then
ringIPBell(params, True)
End If
Dim testvar As String = ex.ToString
Catch ex As Exception
Beep()
End Try
Also, I previously had the following code ringing the bell, but it would only work for one of the two bells, Even though as far as i can tell their settings were identical.
requestStream = wr.GetRequestStream()
strmwrit = New IO.StreamWriter(requestStream)
strmwrit.WriteLine(postdata)
strmwrit.Close()
requestStream.Close()
As suggested I broke out the responestream line as such:
requestStream = wr.GetRequestStream()
strmwrit = New IO.StreamWriter(requestStream)
strmwrit.WriteLine(postdata)
strmwrit.Close()
it breaks on "requestStream = wr.GetRequestStream()"
with the error:
"A first chance exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The operation has timed out"

.NET How to get Sql response to string?

After inserting something into the DB I would like to get the server's response.
For example "x rows effected" or other messages, and put them into a string variable.
How do I implement this in code? C# or VB - doesn't matter to me.
I couldn't find anything specific on this, but I am a n00b # programming.
Thank you kindly.Could you kindly provide an example for me? Here is my code:
Private Function insertScr(ByVal byte2insert As Byte()) As Boolean
Dim _con As SqlConnection
Dim queryStmt As String
Dim _cmd As SqlCommand
Dim param As SqlParameter
Try
_con = New SqlConnection(My.Settings.DBconnStr)
queryStmt = "update ErrorLog set screen = #Content where(ErrorLogID = 2)"
_cmd = New SqlCommand(queryStmt, _con)
param = _cmd.Parameters.Add("#Content", SqlDbType.VarBinary)
param.Value = byte2insert
_con.Open()
_cmd.ExecuteNonQuery()
_con.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function
Assuming SQL Server, the SqlConnection object has an InfoMessage event that is raised for each of these sorts of messages (it also has a mode that can be enabled so that error messages are delivered via the same event, see FireInfoMessageEventOnUserErrors)
You would access the text of these messages by extracting the Message property from the second argument passed to your event handler.
Something like:
...
_con = New SqlConnection(My.Settings.DBconnStr)
AddHandler _con.InfoMessage,Sub(sender,e)
MessageBox.Show(e.Message)
End Sub
queryStmt = "update ErrorLog set screen = #Content where(ErrorLogID = 2)"
...
The ExecuteNonQuery() method of the ADO .NET SQLCommand returns rows affected count.
Stored procedures can return values through output parameters or through RETURN value parameter
Private Function insertScr(ByVal byte2insert As Byte()) As Boolean
Dim _con As SqlConnection
Dim queryStmt As String
Dim _cmd As SqlCommand
Dim param As SqlParameter
Dim RowsAffected as Int
Try
_con = New SqlConnection(My.Settings.DBconnStr)
queryStmt = "update ErrorLog set screen = #Content where(ErrorLogID = 2)"
_cmd = New SqlCommand(queryStmt, _con)
param = _cmd.Parameters.Add("#Content", SqlDbType.VarBinary)
param.Value = byte2insert
_con.Open()
RowsAffected = _cmd.ExecuteNonQuery()
_con.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function

Object reference not set to an instance of an object when calling a function

I call the function GetDataTable and when it gets to the return line, I get the error message:
Object reference not set to an instance of an object.
Dim DB As New DBConn
Dim gd As New DataAccess.GetData
Dim DT As New DataTable
Dim repotid1 As Decimal = 1150
Dim startdata1 As DateTime = "6/1/2012"
Dim EndDate1 As DateTime = "6/12/2012"
Dim StartDate3 As DateTime = "11/1/2011"
Dim Enddate3 As DateTime = "5/1/2012"
Dim sql1 As String = String.Format("EXEC [dbo].[usp_GetReportData_All] #ReportID=N'{0}', #StartDate=N'{1}' #EndDate=N'{2}', #StartDate2=N'{3}' #EndDate2=N'{4}'", repotid1, startdata1, EndDate1, StartDate3, Enddate3)
DT = DB.GetDataTable(sql1)
Public Class DBConn
Dim gd As New DataAccess.GetData
Public Function GetDataTable(ByVal sql As String) As DataTable
Dim _appID As String = "IS"
Dim _transID As String = "MSSQL01"
Return gd.getDataTable(_appID, _transID, sql) 'I get the error message here
End Function
End Class
Updated. I'll see if I can update with the DataAccess.GetData code. I didn't originally put it in there because our shop use it all the time and have no issues with it.
Without seeing what's in gd.getDataTable, there's not a lot we can do to help you. What kind of application are you writing that is calling this function? Can you put a breakpoint on that line in the editor and step into it to see where the error is occurring? Otherwise, do you have access to the DataAccess.GetData code? If so, you would get a lot more information from it if you threw the original exception without destroying the stack trace:
BAD!!!!
Try
'your code
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
GOOD:
Try
'your code
Catch ex As Exception
Throw
End Try