Use public function in sql string - vb.net

I have a project in vb.net that uses a mysql backend. In my project I have a module that contains a number of public functions that I call from different forms. Now I am trying to get data from my db to populate a grid but one of the columns needs to be calculated using one of my public functions. How do I call the function from my SQL string to get the data for that particular column in the grid. I'm getting the data from the db into a datatable and binding it to my grid.
--Edit---
This is the code of the function my want to call from my select query:
Public Function getCurrentQuantity(ByRef ItemID As Integer) As Double
Dim conn As MySqlConnection = New MySqlConnection(gen.connString)
Dim result As Double
Dim recValue As Double 'quantity received
Dim issValue As Double 'quantity issued
Dim adjValueNeg As Double 'negative adjustment of quantity on hand
Dim adjValuePos As Double 'positive adjustment of quantity on hand
Dim p_retValue As Double 'quantity returned to suppliers
Dim i_retValue As Double 'quantity returned to stores
Dim openValue As Double ' opening qty
Dim countLast As Integer = doCount("ID", "inventory_current", " WHERE Item = " & ItemID)
Dim stockDate As Date 'stock date is used to determine where to pick the opening balance from
Dim hasLastStockBal As Boolean 'to determine if the item has a last stock balance
Dim tranTypes As New List(Of String) 'creating a list of the different transaction types to loop through them
tranTypes.AddRange({"RECV", "ISSU", "ADJN", "ADJP", "RETN", "RETI", "OBAL"})
Try
If conn.State <> ConnectionState.Open Then
conn.Open()
End If
If countLast = 0 Then 'no last inventory so opening bal will be from the item table
hasLastStockBal = False
Else
hasLastStockBal = True
End If
For i = 0 To 6 'loop through the list of transaction types
sql = "SELECT SUM(Quantity) FROM stock_dairy WHERE EntryDate > #StockDate AND Item = #Item AND EntryType = #Type"
cmd = New MySqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#StockDate", stockDate)
cmd.Parameters.AddWithValue("#Item", ItemID)
cmd.Parameters.AddWithValue("#Type", tranTypes(i))
da.SelectCommand = cmd
da.Fill(ds, "dat")
rowscount = ds.Tables("dat").Rows.Count
If rowscount = 0 Then
result = 0
Else
If IsDBNull(ds.Tables("dat").Rows(0).Item(0)) Then
result = 0
Else
result = ds.Tables("dat").Rows(0).Item(0)
End If
End If
If i = 0 Then 'assign the retrieved variable based on the For..Next position
recValue = result
ElseIf i = 1 Then
issValue = result
ElseIf i = 2 Then
adjValueNeg = result
ElseIf i = 3 Then
adjValuePos = result
ElseIf i = 4 Then
p_retValue = result
ElseIf i = 5 Then
i_retValue = result
ElseIf i = 6 Then
If hasLastStockBal = True Then
openValue = dLookup("Quantity", "inventory_current", " WHERE Item = " & ItemID)
Else
openValue = result
End If
End If
Next
result = openValue + (((recValue - p_retValue) + adjValuePos) - ((issValue - i_retValue) + adjValueNeg)) 'sum up and return
Return result
Catch ex As Exception
MsgBox(ex.Message, vbExclamation, "Unexpected Error")
Return 0
Finally
ds.Reset()
conn.Dispose()
End Try
End Function

Related

Crystal Reports empty when printed during runtime(without viewer)

I'm developing a small POS system using VB.Net , MS Sql and Crystal Reports. I have no trouble viewing reports using Cry Rep Viewer. But when i try to print a bill during runtime the report becomes empty. Following is the sequence i'm executing within the procedure.
Generate bill no
Deduct qty from stocks
add the transaction from temp table to final sales table
print bill
delete temp table transactions
clear for next transaction
But my problem comes during the bill printing. Bill does not pickup the necessary records from the sales table. Following is my code for the end transaction. (I am using few of my own methods and functions which are from another class and im also using a fix bill no for testing)
I'm also attaching 2 bills. First 1 is the one viewed and exported from the Cry Report Viewer. The second one is the one with problem, and its empty even though the records exists in the table. Can some one kindly advice me on this matter?
Private Sub endCurrentTransaction()
Try
Dim sqlTempBill As String = "SELECT * FROM tb_transactions where cur_user='" & curUser & "'"
Dim sqlSales As String = "SELECT * FROM tb_sales where bill_no=''"
'Get Bill No
Dim newBillNo As String = generateBillNo()
'Deduct IT qty
Dim tempBill As DataTable
tempBill = myTbClass.myFunctionFetchTbData(sqlTempBill)
Dim i As Integer = 0
Dim curQty As Double = 0
Dim trQty As Double = 0
Dim updatedQty As Double = 0
For i = 0 To tempBill.Rows.Count - 1
curQty = 0
'Get the Current stock qty
Dim sqlgetCurQty As String = "SElECT cur_qty FROM tb_stock where it_batch_code='" & tempBill.Rows(i).Item("it_batch_code") & "'"
conn.Open()
Dim SqlCmdCurQty As New SqlCommand(sqlgetCurQty, conn)
Dim DataReadercurQty As SqlDataReader = SqlCmdCurQty.ExecuteReader
While DataReadercurQty.Read()
curQty = DataReadercurQty.Item(0)
End While
DataReadercurQty.Close()
conn.Close()
trQty = tempBill.Rows(i).Item("qty")
updatedQty = curQty - trQty
Dim sqlUpdateQtyString As String = "UPDATE tb_stock SET cur_qty=" & Math.Round((updatedQty), 3) & " Where it_batch_code='" & tempBill.Rows(i).Item("it_batch_code") & "'"
conn.Open()
Dim SqlCmdQty As New SqlCommand(sqlUpdateQtyString, conn)
SqlCmdQty.ExecuteNonQuery()
conn.Close()
'add to sales
Dim tempTbSales As DataTable
tempTbSales = myTbClass.myFunctionFetchTbData(sqlSales)
Dim dataRow As DataRow = tempTbSales.NewRow
dataRow("it_code") = Trim(tempBill.Rows(i).Item("it_code"))
dataRow("it_batch_code") = Trim(tempBill.Rows(i).Item("it_batch_code"))
dataRow("it_name") = Trim(tempBill.Rows(i).Item("it_name"))
dataRow("buy_price") = Math.Round(tempBill.Rows(i).Item("buy_price"), 3)
dataRow("sell_price") = Math.Round(tempBill.Rows(i).Item("sell_price"), 3)
dataRow("qty") = Math.Round(tempBill.Rows(i).Item("qty"), 3)
dataRow("gross_val") = Math.Round(tempBill.Rows(i).Item("gross_val"), 3)
dataRow("discount_val") = Math.Round(tempBill.Rows(i).Item("discount_val"), 3)
dataRow("net_val") = Math.Round(tempBill.Rows(i).Item("net_val"), 3)
dataRow("profit_profile") = Trim(tempBill.Rows(i).Item("profit_profile"))
dataRow("discount_profile") = Trim(tempBill.Rows(i).Item("discount_profile"))
dataRow("cus_name") = Trim(tempBill.Rows(i).Item("cus_name"))
dataRow("tr_type") = Trim(cmbTrans.Text)
dataRow("cr_card_type") = Trim(cmbCardType.Text)
dataRow("card_no") = Trim(txtCardNo.Text)
dataRow("bill_no") = newBillNo
dataRow("discount_profile") = Trim(tempBill.Rows(i).Item("cus_name"))
dataRow("cur_user") = curUser
dataRow("added_date") = curServerDateTime
tempTbSales.Rows.Add(dataRow)
Call myTbClass.MyMethodUpdateTable(sqlSales, tempTbSales)
Next
i = 0
'Print bill
Dim cash, balance As Double
Dim crepBill As New repBill
crepBill.SetDatabaseLogon("sa", dbPwd)
cash = Val(Me.txtCash.Text)
balance = Val(Me.txtBalance.Text)
crepBill.RecordSelectionFormula = "{TB_SALES.bill_no} ='" & "000015" & "'"
crepBill.DataDefinition.FormulaFields("txtCash").Text = Format(cash, "#0.00")
crepBill.DataDefinition.FormulaFields("txtBal").Text = Format(balance, "#0.00")
crepBill.PrintToPrinter(1, False, 0, 0)
crepBill.Dispose()
'delete temp bill table
For i = 0 To tempBill.Rows.Count - 1
tempBill.Rows(i).Delete()
Next
Call myTbClass.MyMethodUpdateTable(sqlTempBill, tempBill)
'reset front end
Call loadBill()
Call clearCurrentTransaction()
Call clearCurrentSubTotals()
Call clearCurCashBalance()
'Íncrease the bill no by 1
Call increaseBillNo()
txtItCode.Focus()
Catch ex As Exception
MsgBox("This error was generated at endCurrentTransaction()")
End Try
End Sub
I found out that report need to be refreshed before printing. Report will only take data if it is refreshed.
https://answers.sap.com/answers/13088178/view.html

function call itself fails to return unique values

What am i doing wrong here. function keeps returning "0001". while i debug it step by step, i figured this line generateNo gets executed again after End function. why is that so?
public class form 1
Dim invCount As integer = 1
End class
Public Function generateInvNo() As String
Dim invString As String
'format invString
If (invCount < 10) Then
invString = "000" + invCount.ToString
ElseIf (invCount > 10 And invCount < 100) Then
invString = "00" + invCount.ToString
ElseIf (invCount > 100 And invCount < 1000) Then
invString = "0" + invCount.ToString
Else
invString = invCount.ToString
End If
'check database to see if invString already exist
Dim conn As New OleDbConnection
conn = accessDB.opendatabase
conn.Open()
Dim dbString As String = "SELECT InvoiceNo FROM INVOICE WHERE InvoiceNo = '" & invString & "' "
Dim dbStringCommand As New OleDbCommand(dbString, conn)
Dim dbReader As OleDbDataReader = dbStringCommand.ExecuteReader
If dbReader.Read Then
'means invoiceNo exist.
invCount += 1
generateInvNo() 'error at here: this line executes again after End function
Else
Return invString
End If
Return 0
End Function
Ignoring other issues, get rid of that final Return 0 and change generateInvNo() to Return generateInvNo(). You have the function calling itself and then ignoring the value returned by that recursive call and just returning 0. How can that be what you intended?

How to add quantity in existing item in DataGridView - vb.net

The problem exists when an item is already in the DataGridView, then when I input again the same item, the quantity and total does not increment or add. It will just list the same item.
e.g.
Item Code ProductName Unit Item Description Price Quantity Total Discount
06-098 Biogesic 500mg Paracetamol 5.50 1 5.50 0.00
It has TextBox to input the barcode and it will list the item in the DataGridView.
Here is my code:
Private Sub txtbxBarcode_TextChanged(sender As Object, e As EventArgs) Handles txtbxBarcode.TextChanged
GetProductInfo()
End Sub
Private Sub GetProductInfo()
Dim discountAmount As Double
Dim medicineName, unit As String
Try
SQL = "SELECT product_code, Medicine_name, Unit, Description, Price, medicineID FROM medicine_info WHERE barcode = '" & txtbxBarcode.Text & "'"
ConnDB()
cmd = New MySqlCommand(SQL, conn)
dr = cmd.ExecuteReader
If dr.Read = True Then
txtbxItemCode.Text = dr("product_code")
unit = dr("Unit")
medicineName = dr("Medicine_name")
txtbxItemDesc.Text = dr("Description")
'Validate Discount
If isDiscount = True Then
discountAmount = Val(dr("Price")) * (Val(discountPercent) / 100)
txtbxPrice.Text = Format(Val(dr("Price")) - discountAmount, "#,##0.00")
Else
txtbxPrice.Text = Format(dr("Price"), "#,##0.00")
discountAmount = 0
End If
'Validate Quantity
If isQuantity = True Then
txtbxQuantity.Text = noOfItems
Else
txtbxQuantity.Text = 1
End If
txtbxTotal.Text = Format(Val(txtbxPrice.Text.Replace(",", "")) * Val(txtbxQuantity.Text), "#,##0.00")
'Adding Item to Gridview to Display
dgv.Rows.Add(dr("medicineID"), dr("product_code"), dr("Medicine_name"), dr("Unit"), dr("Description"), txtbxPrice.Text, txtbxQuantity.Text, txtbxTotal.Text, Format(discountAmount * Val(txtbxQuantity.Text), "#,##0.00"))
'Get Basket Info
BasketInformation()
'Clear Barcode text field
txtbxBarcode.Clear()
'Set Discount to Zero
discountPercent = 0
isDiscount = False
'Set Quantity to False
isQuantity = False
noOfItems = 1
End If
Catch ex As Exception
MsgBox(ex.ToString)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
What I do is loop through the datagridview and look for the matching record i'm going to insert, if there is add +1 to a column, if there isn't insert the row.
Example:
For each row as DataGridViewRow in datagridview1.Rows
If row.Cells(0).Value = dr("ID") Then
row.Cells(6).Value = Integer.Parse(row.Cells(6).Value) + 1
Exit Sub 'Exit Sub for the purpose of not triggering the row add code since there is an existing record already.
End IF
Next
datagridview1.rows.add(....)
You should handle this with the data before placing it into a datagridview. Then when you have the correct data you can just set it as the datasource.
Also for this to work you need to use a datatable instead of reading records row by row. Filling the datatable looks like this..
Dim myTable = new DataTable
Using adapter = New SqlDataAdapter(cmd)
adapter.Fill(myTable)
End Using
And editing the data table looks like this..
For x as Integer = myTable.rows.Count - 1 to 1
For y as Integer = x - 1 to 0
If myTable.rows(x).Item("Item Code") = myTable.rows(y).Item("Item Code") Then
myTable.rows(x).Item("Quantity") = myTable.rows(x).Item("Quantity") + 1
myTable.rows(x).Item("Total") = myTable.rows(x).Item("Total") + myTable.rows(y).item("Total")
myTable.rows(y).Delete()
End If
Next
Next
myTable.acceptChanges()
dgv.dataSource = myTable 'this will put all rows from myTable into the dgv
Hope this helps!

Performance improvement on vb.net code

I need to write 50 million records with 72 columns into text file, the file size is growing as 9.7gb .
I need to check each and every column length need to format as according to the length as defined in XML file.
Reading records from oracle one by one and checking the format and writing into text file.
To write 5 crores records it is taking more than 24 hours. how to increase the performance in the below code.
Dim valString As String = Nothing
Dim valName As String = Nothing
Dim valLength As String = Nothing
Dim valDataType As String = Nothing
Dim validationsArray As ArrayList = GetValidations(Directory.GetCurrentDirectory() + "\ReportFormat.xml")
Console.WriteLine("passed xml")
Dim k As Integer = 1
Try
Console.WriteLine(System.DateTime.Now())
Dim selectSql As String = "select * from table where
" record_date >= To_Date('01-01-2014','DD-MM-YYYY') and record_date <= To_Date('31-12-2014','DD-MM-YYYY')"
Dim dataTable As New DataTable
Dim oracleAccess As New OracleConnection(System.Configuration.ConfigurationManager.AppSettings("OracleConnection"))
Dim cmd As New OracleCommand()
cmd.Connection = oracleAccess
cmd.CommandType = CommandType.Text
cmd.CommandText = selectSql
oracleAccess.Open()
Dim Tablecolumns As New DataTable()
Using oracleAccess
Using writer = New StreamWriter(Directory.GetCurrentDirectory() + "\FileName.txt")
Using odr As OracleDataReader = cmd.ExecuteReader()
Dim sbHeaderData As New StringBuilder
For i As Integer = 0 To odr.FieldCount - 1
sbHeaderData.Append(odr.GetName(i))
sbHeaderData.Append("|")
Next
writer.WriteLine(sbHeaderData)
While odr.Read()
Dim sbColumnData As New StringBuilder
Dim values(odr.FieldCount - 1) As Object
Dim fieldCount As Integer = odr.GetValues(values)
For i As Integer = 0 To fieldCount - 1
Dim vals As Array = validationsArray(i).ToString.ToUpper.Split("|")
valName = vals(0).trim
valDataType = vals(1).trim
valLength = vals(2).trim
Select Case valDataType
Case "VARCHAR2"
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
ElseIf values(i).ToString().Length > valLength Then
sbColumnData.Append(values(i).ToString().Substring(0, valLength))
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadRight(valLength))
'sbColumnData.Append("|")
End If
Case "NUMERIC"
valLength = valLength.Substring(0, valLength.IndexOf(","))
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadLeft(valLength, "0"c))
'sbColumnData.Append("|")
End If
'sbColumnData.Append((values(i).ToString()))
End Select
Next
writer.WriteLine(sbColumnData)
k = k + 1
Console.WriteLine(k)
End While
End Using
writer.WriteLine(System.DateTime.Now())
End Using
End Using
Console.WriteLine(System.DateTime.Now())
'Dim Adpt As New OracleDataAdapter(selectSql, oracleAccess)
'Adpt.Fill(dataTable)
Return Tablecolumns
Catch ex As Exception
Console.WriteLine(System.DateTime.Now())
Console.WriteLine("Error: " & ex.Message)
Console.ReadLine()
Return Nothing
End Try

How to move to next row in dataset and display in hyperlink

I'm writing an email application that will be used to send HTML news articles to clients.
I'm using a dataset to return the headlines to display to the client. When I loop through the dataset the the latest record is returned but latest headline link is not displayed. So the outputted HTML is the same headline everytime, which is the first record in the dataset. How do I move to the next record in the data set and get the outputted HTML to display the next/correct headline?
Here is a sample of my code:
'Code to populate dataset
Public Function GetHeadline(ByVal ArticleID As Integer) As DataSet
Try
Dim objConn As SqlConnection = New SqlConnection()
objConn.ConnectionString = myConnectionString
objConn.Open()
ds = New DataSet
ds.Clear()
Dim sqlCommand As String = "SomeSql"
Dim objCmd As SqlCommand = New SqlCommand(sqlCommand, objConn)
Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter(objCmd)
dataAdapter.Fill(ds)
Catch ex As Exception
MsgBox(ex.ToString)
GetHeadline = Nothing
End Try
Return ds
End Function
'Code to populate link
If GroupID = 4 Then
iLocation1 = HTMLbody.IndexOf("{!HeadlineID")
While iLocation1 > 0
iLocation2 = HTMLbody.IndexOf("}", iLocation1)
sHeadLineTag = HTMLbody.Substring(iLocation1 + 1, iLocation2 - iLocation1 - 1)
dtReport = clsGlobal.globalReportCatalog.GetHeadline2()
clsGlobal.globalReportCatalog.SetHeadlinePropertiesFromRow(dtReport.Rows(0))
With clsGlobal.globalReportCatalog
For i As Integer = 0 To dtReport.Rows.Count
If i < dtReport.Rows.Count - 1 Then
i = i + 1
End If
Dim ID As Integer = dtReport.Rows(i)("ArticleID")
sHyperTag = "" & .HeadlineReportName & " - " & .HeadlineTitle & ""
sHeadlineDescription = .HeadlineDescription
HTMLbody = HTMLbody.Replace("{!Report.Description}", sHeadlineDescription)
Next
End With
I don't see why you need
For i As Integer = 0 To dtReport.Rows.Count
If i < dtReport.Rows.Count - 1 Then
i = i + 1
End If
Can't you use
Dim ID As Integer = dtReport.Rows(dtReport.Rows.Count - 1)("ArticleID")
or was there supposed to be a row movenext in the loop you forgot?