Conversion from empty Date to type 'Date' is not valid - vb.net

My Function works fine until I return an empty or NULL result, then i get the error: Conversion from string "" to type 'Date' is not valid.
VB.NET:
Public Function GetNextWaitListed(ByVal ClassName As String, ByVal ClassDate As Date, ByVal ClassTime As String) As String
Dim connStr As String = ConfigurationManager.AppSettings.Get("TechTrainingConn")
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = "SELECT Min(SubmitTime) FROM [EnrollmentsTbl]" & _
" WHERE [ClassName] = """ & ClassName & """" & _
" AND [ClassDate] = #" & ClassDate & "#" & _
" AND [ClassTime] = """ & ClassTime & """" & _
" AND [Waitlisted] = True" & _
" AND [Completed] = False" & _
" AND [Enrolled] = True"
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
Dim result As Date = comm.ExecuteScalar()
If Not String.IsNullOrEmpty(result) Then
Return result
End If
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Function
I have tried the following but am a little confused since I returning a date
If Not String.IsNullOrEmpty(result) Then
Dim oDate As DateTime = Convert.ToDateTime(result)
Return oDate
End If

The best solution for me was to return into object and if object was empty do the else with dummy date
Public Function GetNextWaitListed(ByVal ClassName As String, ByVal ClassDate As Date, ByVal ClassTime As String) As String
Dim connStr As String = ConfigurationManager.AppSettings.Get("TechTrainingConn")
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = "SELECT Min(SubmitTime) FROM [EnrollmentsTbl]" & _
" WHERE [ClassName] = """ & ClassName & """" & _
" AND [ClassDate] = #" & ClassDate & "#" & _
" AND [ClassTime] = """ & ClassTime & """" & _
" AND [Waitlisted] = True" & _
" AND [Completed] = False" & _
" AND [Enrolled] = True"
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
Dim Obj As Object = comm.ExecuteScalar()
If (Obj IsNot Nothing) AndAlso (Obj IsNot DBNull.Value) Then
Dim matches As String = Obj.ToString
Dim result As Date = Convert.ToDateTime(matches)
Return result
Else
Dim result As Date = Convert.ToDateTime("01/01/1900")
Return result
End If
Catch ex As Exception
Response.Write(ex)
If Not conn Is Nothing Then
conn.Close()
End If
Finally
conn.Close()
End Try
End Function

Related

MS Access Textbox Default Value Max Size Limit

I have the following setup:
I have a form with unbound textbox controls. I have a procedure that fires after every AfterUpdate event.
The procedure sends the input value to a table and returns the value input in the table as the textbox's DefaultValue. The table defines unique rows by the form and control name, 2 primary keys.
After data is input, there is a button that sends data from the form in a structured way to another table and a report reads off the table. The data is input into the table in a structured way with an SQL query.
The problem is when a user inputs texts over 2048 characters in two of the fields, the code breaks due to the limit. Two of the fields on the form, on each page will likely have over 2k characters due to the nature of the forms.
My question is, can I circumvent, increase or bypass the character limit?
My code is posted below for reference if needed (Procedure called OptimizeS is loaded in every textbox on the form):
Procedure that writes the input value to the table:
Private Sub OptimizeS()
Dim cmd As ADODB.Command
Dim strForm As String
Dim strControl As String
Dim strSQL As String
Dim strCriteria As String
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strCriteria = "FormName = """ & Me.Name & """ " & _
"And ControlName = """ & Me.ActiveControl.Name & """"
' is there an existing default for this control?
If Not IsNull(DLookup("FormName", "Defaults", strCriteria)) Then
' if so then update row in table
strSQL = "UPDATE Defaults " & _
"SET DefaultVal = """ & Me.ActiveControl & """ " & _
"WHERE " & strCriteria
Else
' insert new row
strSQL = "INSERT INTO Defaults(" & _
"FormName,ControlName,DefaultVal) " & _
"VALUES(""" & Me.Name & """,""" & _
Me.ActiveControl.Name & """,""" & _
Me.ActiveControl & """)"
End If
cmd.CommandText = strSQL
cmd.Execute
End Sub
Support Procedures on the form itself:
1)
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim cmd As ADODB.Command
Dim strOpened As String
Dim strForm As String
Dim strSQL As String
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strOpened = "Opened = """ & Me.Name & """ "
If Not IsNull(DLookup("Opened", "AllOpened", strOpened)) Then
strSQL = "UPDATE AllOpened " & _
"SET Opened = """ & Me.Name & """ " & _
"WHERE " & strOpened
Else
strSQL = "INSERT INTO AllOpened(Opened) " & _
"VALUES(""" & Me.Name & """)"
End If
cmd.CommandText = strSQL
cmd.Execute
End Sub
2)
Private Sub Form_Open(Cancel As Integer)
Dim cmd As ADODB.Command
Dim strCriteria As String
Dim strOpened As String
Dim varDefault As Variant
Dim varOpened As Variant
Dim strForm As String
Dim strSQL As String
Dim ctrl As Control
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strOpened = "Opened = """ & Me.Name & """ "
varOpened = DLookup("Opened", "AllOpened", strOpened)
If IsNull(varOpened) Then
strSQL = "INSERT INTO AllOpened(Opened) " & _
"VALUES(""" & Me.Name & """)"
cmd.CommandText = strSQL
cmd.Execute
Else
GoTo ErrMsg
End If
For Each ctrl In Me.Controls
strCriteria = "FormName = """ & Me.Name & """ " & _
"And ControlName = """ & ctrl.Name & """"
varDefault = DLookup("DefaultVal", "Defaults", strCriteria)
If Not IsNull(varDefault) Then
ctrl.DefaultValue = """" & varDefault & """"
End If
Next ctrl
Exit Sub
ErrMsg:
MsgBox ("The form is already open by another user. Please double-check before editing."), , "Important!!!"
End Sub
3)
Private Sub Form_Unload(Cancel As Integer)
Dim strSQL As String
Dim strForm As String
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strSQL = "DELETE FROM AllOpened " & _
"WHERE Opened = """ & Me.Name & """"
cmd.CommandText = strSQL
cmd.Execute
End Sub
That's a hint in your last comment. Then try this verbose code using string variable that for sure doesn't have a 2K limit:
Dim DefaultString As String
DefaultString = Nz(varDefault)
ctrl.DefaultValue = DefaultString

VB2008 Changing string in a file

I want to change something on a compiled game file, so I used this code:
Private Sub Next2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Next2.Click
Dim reader As New System.IO.StreamReader("Languages/" & Language & ".Devil")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
Tips.Text = ReadLine(6, allLines)
WeaponsListBox.Hide()
NewWeaponsList.Hide()
Next2.Hide()
Dim curItem As String = WeaponsListBox.SelectedItem.ToString()
Dim curItem2 As String = NewWeaponsList.SelectedItem.ToString()
Try
If MainWeapon = "Cheytac" Then
Dim supahotfire As String = curItem.Substring(0, 12)
Dim hotdestroyer As String = curItem.Replace(supahotfire, "")
Dim supa2 As String = curItem2.Substring(0, 12)
Dim hot2 As String = curItem2.Replace(supa2, "")
Dim oldfile As String = "pack/Weapon_" & curItem & ".i3pack"
Dim FileName As String = "pack/pack_" & MainWeapon & hot2 & "_" & hotdestroyer & ".i3pack"
Dim be = My.Computer.FileSystem.ReadAllBytes(oldfile)
Dim be2 As String = UnicodeBytesToString(be)
be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
Dim be3 As String = be2.Replace("Weapon\" & curItem & "/Cheytac_M200_Diff.i3i", "Weapon\" & curItem2 & "/Cheytac_M200_Diff.i3i")
Dim be4 = UnicodeStringToBytes(be3)
My.Computer.FileSystem.WriteAllBytes(FileName, be4, True)
'System.IO.File.AppendAllText(FileName, be4)
' Dim fs As FileStream = New FileStream(oldfile, FileMode.Open)
' Dim br As BinaryReader = New BinaryReader(fs)
'Dim bin as byte[]= br.ReadBytes(Convert.ToInt32(fs.Length));
' fs.Close()
'br.Close()
End If
Catch ex As Exception
System.IO.File.AppendAllText("MathimaticalErrors.txt", ex.ToString)
End Try
End Sub
Public Function UnicodeBytesToString(ByVal bytes() As Byte) As String
Return System.Text.Encoding.Unicode.GetString(bytes)
End Function
Public Function UnicodeStringToBytes(ByVal str As String) As Byte()
Return System.Text.Encoding.Unicode.GetBytes(str)
End Function
The problem is that the newly created file is basically the same as the old file, and nothing has changed on it. How can I solve this?
At this point in your code:
Dim be2 As String = UnicodeBytesToString(be)
be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
The value in be2 would remain unchanged. You have to store the return value of Replace():
Dim be2 As String = UnicodeBytesToString(be)
be2 = be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
Also, at this line:
My.Computer.FileSystem.WriteAllBytes(FileName, be4, True)
The True at the end means you want to append the bytes. If the file is empty this will be fine. If not, then you'll end up adding the bytes to the end of the file each time. Not sure if that is your intended result...

Microsoft Query in Excel SQL Criteria Variant Type causes OLE error

Public Sub SQLSelect(connection As String, range1 As Excel.range, _
range2 As Excel.range, Optional range1name As String, Optional range2name As String,_
Optional varparameter As Variant, Optional varcriteria As Variant, _
Optional varnot As Variant, Optional sdestination As String,_
Optional srangename As String, Optional sqlrange As String)
Dim sselect As String
Dim cn As ADODB.connection
Dim rs As ADODB.Recordset
Dim cm As ADODB.Command
Dim pm As ADODB.Parameter
Dim iiterator As Integer
Dim varcriteriterator As Variant
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.recordset")
Set cm = New ADODB.Command
sselect = "SELECT " & range1name & ".ENTITYREF, SUM(" & range1name & ".AMT), SUM(" & range2name & ".AMT) FROM " & range1name & " " & range1name & " INNER JOIN " & range2name & " " & range2name & " ON " & range1name & ".ENTITYREF" & " = " & range2name & ".ENTITYREF WHERE "
cn.Open (connection)
With cm
.ActiveConnection = cn
.CommandType = adCmdText
For iiterator = 0 To UBound(varparameter)
If iiterator = 0 Then
sselect = sselect & range1name & "." & varparameter(iiterator) & " = ? "
Else
sselect = sselect & " AND " & range1name & "." & varparameter(iiterator) & " = ? "
End If
If Not CStr(varcriteria(iiterator)) = varcriteria(iiterator) Then
For Each varcriteriterator In varcriteria
Set pm = .CreateParameter(varparameter(iiterator), adNumeric, adParamInput)
If varnot(iiterator) = 0 Then
pm.Value = varcriteriaiterator
ElseIf varnot(iiterator) = 1 Then
pm.Value = "NOT" & varcriteriaiterator
End If
cm.Parameters.Append pm
Next
Else
Set pm = .CreateParameter(varparameter(iiterator), adNumeric, adParamInput)
If varnot(iiterator) = 0 Then
pm.Value = varcriteria(iiterator)
ElseIf varnot(iiterator) = 1 Then
pm.Value = "NOT" & varcriteria(iiterator)
End If
.Parameters.Append pm
End If
Next iiterator
End With
sselect = sselect & "GROUP BY " & range1name & ".ENTITYREF HAVING(((Count(" & range1name & ".AMT))>1) AND ((Count(" & range2name & ".AMT))>1));"
cm.CommandText = sselect
Set rs = cm.Execute
ThisWorkbook.Sheets("SourcePivot").range(sdestination).CopyFromRecordset rs
ThisWorkbook.Sheets("SourcePivot").range(sdestination, ThisWorkbook.Sheets("SourcePivot").range(sdestination).End(xlDown).Offset(, 2)).Name = srangename
ThisWorkbook.Sheets("Interface").range(sqlrange).Value = sselect
The above code is intended to create a query within an excel workbook which can be passed two ranges of data and create a functional SQL statement through microsoft query to draw the information into a destination range. VarNot is an array of 1&0's which mark whether the matching criteria should be a NOT, and the SQL range is a destination cell which houses the query for troubleshooting.
I have received the following error:
Multi-Step OLE DB operation generated errors. Check each OLE DB Status
value, if available. No work was done.
This is after the code executed properly and create a well-formed query:
SELECT Case1.ENTITYNUM, SUM(Case1.AMT), SUM(Case2.AMT) _
FROM Case1 Case1 INNER JOIN Case2 Case2 ON Case1.ENTITYNUM = Case2.ENTITYNUM _
WHERE Case1.Code = ? AND Case1.YEAR = ? _
GROUP BY Case1.ENTITYNUM HAVING(((Count(Case1.AMT))>1) AND ((Count(Case2.AMT))>1));
I will end passing the module a variety of criteria and parameters, but the parameters are, at this point, exclusive an array of text strings. The criteria are arrays of strings and ranges, which I believe is causing the issue.
I would appreciate any help in solving the error and successfully parameterizing this query with an array that may contain a string or variant range of cells.

Batching results SQL Server 2008 R2

How would I go about batching records in a select statement I Have to conserve bandwidth as delaying with shop tills so bandwidth is at a premium. I will be reading the batch size from configuration file and passing to this select statement:
Friend Function SelectAllPendingDeliveries() As String Implements iScriptBuilder.SelectAllPendingDeliveries
Dim retVal As String = ""
retVal = "Select * from batchtable where [location] is not null and isprocessed = 0"
Return retVal
End Function
How would I go about doing this is the table structure
#Anthoy I think this is where I am getting tripped up how Would i control it here to for it to loop until the end of the recordset so it executes in batches this is the function that calls the select statement
#Anthory I meen this code i pasted the wrong proc in
Friend Function CreateLiveSale(ByVal wrpPush As LiveSales.wrpPush, ByVal rCount As Int32, ByVal request As LiveSales.requestPush, ByVal orderLineData As DataTable, ByVal packetBatchSize As String) ', ByVal orderNumber As String, ByVal orderLineReference As String, ByVal uniqueFilename As String, ByVal tagBarCode As String, ByVal costPrice As String, ByVal deliveryQty As Int32, ByVal orderLineData As DataTable) As Boolean
Dim retVal As Boolean
Dim settings As LiveSalesBackOfficeClient.infoLiveSalesBackOfficeClient = _
(New LiveSalesBackOfficeClient.configurationLoader).LoadConfiguration
Dim cfb As New cfbConfiguration
Dim pushOrderIncQTY As New infoPushOrderIncQTY()
Dim totalRecords As Integer = orderLineData.Rows.Count
Dim pushOrderInc As List(Of infoPushOrderIncQTY) = New List(Of infoPushOrderIncQTY)() ' create a generic list
Dim recordCount As Integer = 0
Dim batchNumber As Integer
Dim batchNumberpad As String
Dim filenameSplit As String()
For Each thisentry In orderLineData.Rows
If recordCount = 0 Then
filenameSplit = thisentry.Item("unqiueFilename").ToString().Split("_")
batchNumber = recordCount + 1
batchNumberpad = Path.GetFileNameWithoutExtension(filenameSplit(2)) & "_" & batchNumber.ToString("D3") & ".csv"
With request
.companyID = settings.companyID
.machineID = settings.machineID
.uniqueBatchIdentifier = batchNumberpad
End With
End If
With pushOrderIncQTY
.costPrice = thisentry.Item("costPrice")
.externalTimeStamp = DateTime.Now()
.RootPLU = thisentry.Item("tagbarcode") 'set this to the barcode from the file
.sizeBit = -666
.supplierID = cfb.SupplierID
.orderReference = thisentry.Item("OrderNumber")
.orderLineReference = ""
.externalTransaction = ""
.sourceShop = cfb.SiteId 'set to the GEMINI location ID for this store (you will have to get this from your configuration file
.destinationShop = cfb.SiteId 'set this to the same as the sourceshop
.QTY = thisentry.Item("ActQty")
.whichQty = LiveSales.infoPushOrderIncQTY.Which_OrderQty.delivered 'only available option at present
End With
recordCount = recordCount + 1
pushOrderInc.Add(pushOrderIncQTY) ' add it to the list for batching
If recordCount = cfb.PacketBatchSize Then ' only when the record count = the packetsize fire off
pushOrderInc.Clear()
recordCount = 0
End If
If cfb.PacketBatchSize > 0 Then
CallWebSerivce(wrpPush, request, pushOrderInc.ToArray())
End If
Next
If cfb.PacketBatchSize = 0 Then ' if their is a batch size then lets just processe
'call the webservice
CallWebSerivce(wrpPush, request, pushOrderInc.ToArray())
End If
Return retVal
End Function
#anthoy the above gets called by this procedure so it does its hear the looping needs to happen
OpenConnection()
Dim results As DataTable = connection.SqlSelectToDataTable(scriptBuilder.SelectAllPendingDeliveries)
Dim dataForEmail As String = ""
Dim msg As String = ""
msg = "The Following Deliverys where processed for the Following Ordernumbers at " & DateTime.Now.ToString() & Chr(13)
dataForEmail = "Order Number" & vbTab & "BarCode" & vbTab & vbTab & vbTab & "Product Name" & vbTab & vbTab & vbTab & vbTab & vbTab & "Brand" & vbTab & vbTab & vbTab & "Size" & vbTab & vbTab & "Colour" & vbTab & "Qty" & vbTab & vbTab & "RRP" & vbTab & Chr(13)
Dim totalcost As Decimal
Dim cnt As Int16 = 0
Dim fileName As String = ""
If Not IsNothing(results) AndAlso Not IsNothing(results.Rows) _
AndAlso results.Rows.Count > 0 Then
Dim rrpprice As Double = 0.0
For Each thisRow As DataRow In results.Rows
If IsDBNull(thisRow.Item("RRPPrice")) Then
rrpprice = 0.0
Else
rrpprice = thisRow.Item("RRPPrice")
End If
fileName = thisRow.Item("unqiueFilename")
totalcost = totalcost + rrpprice * thisRow.Item("QTY")
dataForEmail = dataForEmail & BuildReportFoEmail(thisRow)
connection.ExecuteNonQuerySql(scriptBuilder.SetDeliveryStatus(2, 1, thisRow.Item("r3DeliveryId")))
cnt = cnt + 1
Next
connection.ExecuteNonQuerySql(scriptBuilder.SetDeliveryStatus(1, 0))
CreateLiveSalesDeliveryForR3(cnt, fileName, results, cfb.PacketBatchSize)
dataForEmail = dataForEmail & vbCrLf & "Total Price " & totalcost.ToString() & vbCrLf & BuildExceptionsForEmail(results) & vbCrLf
End If
SendEmailViaWebService(dataForEmail, cfb.EmailForDeliverys, cfb.FullNameForEmailSubject, msg)
MsgBox("Delvery Complete", vbInformation, "Delivery Import")
CloseConnection()

Read a text file which contains SQL code to create tables in a database

I need code to read a .txt file which is in my project bin\debug directory that contains SQL code to create tables in a large number it size of 936kb
This following code only I'm using...
By using this it gives result like table created but it is not reading the file... there is nothing in the database
Public Function readTextFile(ByVal fileName As String) As String
Dim strContent As String()
Dim x As String = ""
Try
'fileName = "CSYSS802.txt"
If Not System.IO.File.Exists(fileName) Then
'o Until EOF()
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x = x + Str
Next
readTextFile = x
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
readTextFile = x
End Function
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), "GO")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "")
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
In the readTextFile function, it will only attempt to read the text from the text file if the file DOESN'T exist. If the text file exists then the function returns an empty string and if the text file doesn't exist, the function will throw a file not found exception.
Replace:
If Not System.IO.File.Exists(fileName) Then
with:
If System.IO.File.Exists(fileName) = True Then
You might also want to include an Else clause in case the file doesn't exist as it won't throw an error since you have handled it correctly.
If System.IO.File.Exists(fileName) = True Then
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x &= Str
Next
Return x
Else
MessageBox.Show("The file '" & fileName & "' does not exist.")
Return ""
End If
My Self I had Found The solution..I attache the Following Code...It now Creating All tables Properly..
Make sure that each Sql Commands in your Text File ends with go.. because i used "GO" Keyword to split the text...
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), " GO ")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "", sqlCon1)
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
Public Function readTextFile(ByVal file As String) As String
Dim fso As New System.Object
Dim ts As Scripting.TextStream
Dim sLine As String
fso = CreateObject("Scripting.FileSystemObject")
ts = fso.openTextFile(file)
Do Until ts.AtEndOfStream
sLine = sLine & " " & ts.ReadLine
Loop
ts.Close()
fso = Nothing
readTextFile = sLine
End Function