Why is IsDBNull throwing a conversion overflow exception? - asp.net

I have a pretty simple code snippet here that is causing me a lot of problems. I also want to mention that using statements should be used, but the code was not originally authored by me. I'll likely fix this at some point
Dim dbShippableOpenOrders As New sqlCommand(sqlText, objConn)
Dim rsShippableOpenOrders As sqlDataReader = dbShippableOpenOrders.executeReader
...
If IsDBNull(rsShippableOpenOrders("cost")) Then
cost = 0
Else
cost = rsShippableOpenOrders("cost")
End If
I can't seem to figure out why this code is producing the following error message:
Conversion overflows.
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.OverflowException: Conversion overflows.
Source Error:
Line 355: End If
Line 356:
Line 357: If IsDBNull(rsShippableOpenOrders("cost")) Then
Line 358: cost = 0
Line 359: Else

Try the following:
Dim cost As Decimal = 0
Dim dbShippableOpenOrders As New SqlCommand(sqlText, objConn)
Dim rsShippableOpenOrders As SqlDataReader = dbShippableOpenOrders.ExecuteReader()
If rsShippableOpenOrders.HasRows Then
While rsShippableOpenOrders.Read()
If rsShippableOpenOrders("cost") IsNot Nothing AndAlso Not IsDBNull(rsShippableOpenOrders("cost")) Then
cost = CDec(rsShippableOpenOrders("cost"))
Else
cost = 0
End If
End While
End If
Here's a sample method:
Public Sub GetDataTblProduct(connectionStr As String)
Dim sqlText As String = "Select * from Product"
Dim cost As Decimal = 0
Using con As SqlConnection = New SqlConnection(connectionStr)
'open
con.Open()
Using dbShippableOpenOrders As SqlCommand = New SqlCommand(sqlText, con)
Using rsShippableOpenOrders As SqlDataReader = dbShippableOpenOrders.ExecuteReader
If rsShippableOpenOrders.HasRows Then
While rsShippableOpenOrders.Read()
If rsShippableOpenOrders("cost") IsNot Nothing AndAlso Not IsDBNull(rsShippableOpenOrders("cost")) Then
cost = CDec(rsShippableOpenOrders("cost"))
Else
cost = 0
End If
'Debug.WriteLine("cost: " & cost)
End While
End If
End Using
End Using
End Using
End Sub

Related

Managing licenses for Office 365 in vb.net

I am trying to run Office365 cmdlets in a vb.net webservice project.The code is:
Public Function ExcutePowershellCommands() As ObjectModel.Collection(Of PSObject)
Try
Dim userList As ObjectModel.Collection(Of PSObject) = Nothing
Dim initialSession As InitialSessionState = InitialSessionState.CreateDefault()
initialSession.ImportPSModule(New String() {"MSOnline"})
Dim O365Password_secureString As New System.Security.SecureString()
Dim O365Password As String = "password"
For Each x As Char In O365Password
O365Password_secureString.AppendChar(x)
Next
Dim credential As New PSCredential("username", O365Password_secureString)
Dim connectCommand As New Command("Connect-MsolService")
connectCommand.Parameters.Add((New CommandParameter("Credential", credential)))
Dim getCommand As New Command("Get-MsolUser")
Using psRunSpace As Runspace = RunspaceFactory.CreateRunspace(initialSession)
psRunSpace.Open()
For Each com As Command In New Command() {connectCommand, getCommand}
Dim pipe As Pipeline = psRunSpace.CreatePipeline()
pipe.Commands.Add(com)
Dim results As ObjectModel.Collection(Of PSObject) = pipe.Invoke()
Dim [error] As ObjectModel.Collection(Of Object) = pipe.[Error].ReadToEnd()
If [error].Count > 0 AndAlso com.Equals(connectCommand) Then
Throw New ApplicationException("Problem in login! " + [error](0).ToString())
Return Nothing
End If
If [error].Count > 0 AndAlso com.Equals(getCommand) Then
Throw New ApplicationException("Problem in getting data! " + [error](0).ToString())
Return Nothing
Else
userList = results
End If
Next
psRunSpace.Close()
End Using
Return userList
Catch generatedExceptionName As Exception
Throw
End Try
End Function
When Connect-MsolService is run, I get this error message:
There was no endpoint listening at https://provisioningapi.microsoftonline.com/provisioningwebservice.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
I can run this function successfully within a windows App. I think some thing might be wrong in IIS. any idea?

Connection property has not been initialized when filling a DataSet

So here is my issue:
Currently I am trying to make a report that will show 1st and 2nd shifts, by multiple days...
So if they select the range 6/02 - 6/04, I am running a query 3 times... once for 6/02, 6/03, and 6/04... Also they can select shift, so it would be those dates, but 4:30AM-4:30PM for 1st shift....
Currently I have a error, when trying to put my queries/calls inside the for loop... I calculate the difference of the two dates and set them up fine, its just my connection string gives me the error:
If the image is not easy to see here is a text description of the error:
Server Error in '/mfgx_test' Application.
Fill: SelectCommand.Connection property has not been initialized.
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: Fill:
SelectCommand.Connection property has not been initialized.
Source Error:
Line 623: Dim dsTop1 As New DataSet Line 624: Dim daTop1
As New SqlDataAdapter(strSql, myCn1) Line 625:
daTop1.Fill(dsTop1) Line 626: Line 627: myCn1.Close()
Source File: C:\inetpub\wwwroot\mfgx_test\defectsbyround.aspx.vb
Line: 625
Which leads me to beleive that something is wrong with my connection string being outside of my for loop... My code is as follows (Although a bit cleaned up so it is easier to read):
Dim myCn1 As New SqlConnection
myCn1.ConnectionString = "server=Blah;database=Blah;user id=Blah;password=Blah"
myCn1.Open()
For i = 0 To Session("DaysDiff")
strSql = "Blah.Blah"
Dim dsTop1 As New DataSet
Dim daTop1 As New SqlDataAdapter(strSql, myCn1)
daTop1.Fill(dsTop1)
myCn1.Close()
myCn1 = Nothing
If dsTop1.Tables(0).Rows.Count > 0 Then
spitout2(dsTop1)
End If
txtStartdate.Text = DateAdd("d",1,txtStartdate.Text)
txtEnddate.Text = DateAdd("d",1,txtEnddate.Text)
Next
That's because you are closing the connection inside your loop and so for next iteration there is no open connection present and hence the exception (see pointed below)
myCn1.Close()
myCn1 = Nothing
You should declare the Dataset and tableadapter as well out side the loop context. Your code should somewhat look like below
Dim myCn1 As New SqlConnection
myCn1.ConnectionString = "server=Blah;database=Blah;user id=Blah; password=Blah"
myCn1.Open()
Dim dsTop1 As New DataSet
Dim daTop1
For i = 0 To Session("DaysDiff")
strSql = "Blah.Blah"
daTop1 As New SqlDataAdapter(strSql, myCn1)
daTop1.Fill(dsTop1)
.......
Next
myCn1.Close()
myCn1 = Nothing
Assuming you want to reuse the connection inside the loop, release the connection automatically with a Using statement outside the for loop
Using myCn1 As New SqlConnection("server=Blah;database=Blah;user id=Blah;password=Blah")
myCn1.Open()
For i = 0 To Session("DaysDiff")
strSql = "Blah.Blah"
Dim dsTop1 As New DataSet
Dim daTop1 As New SqlDataAdapter(strSql, myCn1)
daTop1.Fill(dsTop1)
If dsTop1.Tables(0).Rows.Count > 0 Then
spitout2(dsTop1)
End If
txtStartdate.Text = DateAdd("d",1,txtStartdate.Text)
txtEnddate.Text = DateAdd("d",1,txtEnddate.Text)
Next
End Using
When End Using is reached, SqlConnection.Dispose() will be called, releasing connection resources.

Comparing variables to SQL / Troubleshooting session

I am trying to send some variables, using a session, to the next page "ProcedureSelectionForm.aspx". As you can see, the sessions have been commented out. The code below will work (without sending the variable of course). However, when you remove the comments the .onclick function reloads the page rather than navigating to "ProcedureSelectionForm.aspx". For this reason, I believe this is where my problem is. The first two columns are "Account" and "Password" in the database. I have not misspelled anything. I am new to VB and ASP.net and would appreciate some explanation as to what is happening and why my desired functionality isn't materializing. Thank you for your help!
If IsValid Then
Try
Dim strSQL = "select * from CreatePatient where Account = #Account and Password = #Password"
Using CCSQL = New SqlConnection(ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString)
Using CCUser = New SqlCommand(strSQL, CCSQL)
CCSQL.Open()
CCUser.Parameters.Add("#Account", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#Password", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCUser.ExecuteNonQuery()
'Using reader As SqlDataReader = CCUser.ExecuteReader()
'If reader.HasRows Then
'reader.Read()
'Session("user") = reader("Account")
'Session("pass") = reader("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
'End If
'End Using
End Using
End Using
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
My friend was able to make time to help me out. I am unsure of what he did differently besides closing connections
If IsValid Then
Dim CCSQL As New SqlConnection
Dim CCUser As New SqlCommand
Dim strSQL As String
Dim dtrUser As SqlDataReader
Try
CCSQL.ConnectionString = ConfigurationManager.ConnectionStrings("CreatePatientConnectionString").ConnectionString
strSQL = "Select * from CreatePatient where Account=#user and Password=#pwd"
CCUser.CommandType = Data.CommandType.Text
CCUser.CommandText = strSQL
CCUser.Parameters.Add("#user", Data.SqlDbType.VarChar).Value = PatientAccount.Text
CCUser.Parameters.Add("#pwd", Data.SqlDbType.VarChar).Value = PatientPass.Text
CCSQL.Open()
CCUser.Connection = CCSQL
dtrUser = CCUser.ExecuteReader()
If dtrUser.HasRows Then
dtrUser.Read()
Session("user") = dtrUser("Account")
Session("level") = dtrUser("Password")
Response.Redirect("ProcedureSelectionForm.aspx")
Else
Label1.Text = "Please check your user name and password"
End If
dtrUser.Close()
CCSQL.Close()
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
I am on a tight deadline but i will get back to those interested with an answer. Thank you for your effort.
You don't want to do .ExecuteNonQuery() when you are actually doing a query (i.e. a SQL "SELECT" statement. You can just do the .ExecuteReader() to read those two values.
Also, I presume you are trying to validate the Account and Password; otherwise you could just set Session("user") = PatientAccount.Text and set Session("pass") = PatientPass.Text.

error when trying to update column values in VB.net

Good day!
I just want to seek help from you guys, I'm again having problems with my UPDATE functionality, here's my code...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con = New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
con.Open()
Dim cmd As SqlCommand = con.CreateCommand
cmd.CommandText = String.Format("UPDATE trip SET ticketno, charge, driver, destination, passenger, purpose, tripdate", txtticket.Text, txtcharge.Text, txtdriver.Text, txtdestination.Text, txtpassenger.Text, txtpurpose.Text, dtptripdate1.Value)
Dim affectedRows As Integer = cmd.ExecuteNonQuery
If affectedRows > 0 Then
MsgBox("Succesfully Updated")
Else
MsgBox("Failed to update")
End If
con.Close()
End Sub
When I try to click the Button, an error would show:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near ','.
thanks for helping me out.
I'm really close to finishing this small-scale project for my office but I'm stuck with these kind of problems.
Try this,
Dim myCommand = New SqlCommand("UPDATE trip SET ticketno=#ticketno, charge=#charge, driver=#driver, destination=#destination, passenger=#passenger, purpose=#purpose, tripdate=#tripdate",con)
myCommand.Parameters.Add("#ticketno", txtticket.Text)
myCommand.Parameters.Add("#charge", txtcharge.Text)
myCommand.Parameters.Add("#driver", txtdriver.Text)
myCommand.Parameters.Add("#destination", txtdestination.Text)
myCommand.Parameters.Add("#passenger", txtpassenger.Text)
myCommand.Parameters.Add("#purpose", txtpurpose.Text)
myCommand.Parameters.Add("#tripdate", dtptripdate1.Text)
Dim affectedRows As Integer = cmd.ExecuteNonQuery
If affectedRows > 0 Then
MsgBox("Succesfully Updated")
Else
MsgBox("Failed to update")
End If
con.Close()
Your UPDATE statement is wrong, so your String.Format. and don't your missed out a WHERE condition?
cmd.CommandText = String.Format("UPDATE trip SET ticketno='{0}', charge='{1}', driver='{2}', destination='{3}', passenger='{4}', purpose='{5}', tripdate='{6}'", txtticket.Text, txtcharge.Text, txtdriver.Text, txtdestination.Text, txtpassenger.Text, txtpurpose.Text, dtptripdate1.Value)
OR try this to avoid SQL Injection.
Wrap your conn with a Using block to ensure the dispose of your SqlConnection
Using conn As New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
conn.Open()
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandText = "UPDATE trip SET ticketno=#ticketno, charge=#charge, driver=#driver, destination=#destination, " & _
"passenger=#passenger, purpose=#purpose, tripdate=#tripdate " & _
"WHERE SomeCondition"
cmd.Parameters.AddWithValue("#ticketno", txtticket.Text)
cmd.Parameters.AddWithValue("#charge", txtcharge.Text)
cmd.Parameters.AddWithValue("#driver", txtdriver.Text)
cmd.Parameters.AddWithValue("#destination", txtdestination.Text)
cmd.Parameters.AddWithValue("#passenger", txtpassenger.Text)
cmd.Parameters.AddWithValue("#purpose", txtpurpose.Text)
cmd.Parameters.AddWithValue("#tripdate", dtptripdate1.Value)
Dim affectedRow As Integer = cmd.ExecuteNonQuery
IIf(affectedRow > 0, MsgBox("Succesfully Updated"), MsgBox("Failed to update"))
End Using

how to maintain connection with excel with rapidly data fetching

i am making a website for trading, with trading feeds coming from a source in an excel sheet. I have to show data from the excel sheet in a gridview. When i make connection it will fail due to rapidly changing data; each cell in the sheet changes value 1-3 times per second. I am using an Ajax Timer of interval 100. Here is my code:
Public Function RetrieveExcelData(ByVal excelSheetName As String, ByVal sheetNumber As Integer) As DataSet
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
' Connection String.
Dim connString As [String] = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\Vishal\Desktop\TESTING COLOURfor web1.xls;Extended Properties=Excel 8.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString()
i += 1
If i = sheetNumber Then
Exit For
End If
Next
Dim excelCommand As New OleDbCommand("Select * from [" + excelSheets(sheetNumber - 1) & "]", objConn)
Dim excelAdapter As New OleDbDataAdapter(excelCommand)
Dim excelDataSet As New DataSet()
excelAdapter.Fill(excelDataSet)
Return excelDataSet
Catch ex As OleDbException
Throw ex
Catch ex As Exception
Throw ex
Finally
' Clean up.
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
End Function
To be honest - I cannot see how it can work. You are trying to use Excel spreadsheet as a database to store and retrieve data in real-time, for which Excel was never intended or designed.
You have mentioned that the Excel gets data several times per second. What is the source of data? RTD component? Bloomberg API? I would try to avoid the middle step of storing data in a spreadsheet.

Resources