Convert Dataset into String in VB - asp.net

I am having an error with compiling the codes. It says that dataset cant be converted to string.. Please help me.. I have done this by using SQL Stored procedure.. I have to get the employee name saved in master table to retrieve the ID and then ID should retrieve the leave details from leave details table.
Public Shared Function GetEmpID(ByVal EmpName As String) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase(HttpContext.Current.Session("CompanyID").ToString) ' TO Get Database Connection
Dim dbCommand As DbCommand = db.GetStoredProcCommand("spRetrieveEmpID") ' Stored Procedure to Execute
db.AddInParameter(dbCommand, "EmployeeName", DbType.String, EmpName) ' Parameter for Stored Procedure
Return db.ExecuteDataSet(dbCommand) ' Execute Stored Procedure
End Function
Public Shared Function EmpLeaveDetails(ByVal EmployeeID As String) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase(HttpContext.Current.Session("CompanyID").ToString) ' TO Get Database Connection
Dim dbCommand As DbCommand = db.GetStoredProcCommand("spHRLeaveEntitlement") ' Stored Procedure to Execute
db.AddInParameter(dbCommand, "EmployeeID", DbType.String, EmployeeID) ' Parameter for Stored Procedure
Return db.ExecuteDataSet(dbCommand) ' Execute Stored Procedure
End Function
And this is my leave.aspx.vb codes
Private Sub ddlEmpName_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs) Handles ddlEmpName.SelectedIndexChanged
EmployeeID = TESTING.GetEmpID(ddlEmpName.Text)
If ds.Tables(0).Rows.Count > 0 Then
dgLeaveDetails.DataSource = ds
dgLeaveDetails.DataBind()
End If
ds1 = TESTING.EmpLeaveDetails(EmployeeID)
dgLeaveDetails.DataSource = ds1
ddlEmpName.SelectedIndex = -1
dgLeaveDetails.Rebind()
End Sub

The line
EmployeeID = TESTING.GetEmpID(ddlEmpName.Text)
looks like the problem to me.
You should use:
Dim dst As Dataset = TESTING.GetEmpID(ddlEmpName.Text)
EmployeeID = CStr(dst.Tables(0).Rows(0).Item("EmployeeID"))

You are setting EmployeeID, like this:
EmployeeID = TESTING.GetEmpID(ddlEmpName.Text)
The GetEmpID method returns a DataSet object. Therefore, EmployeeID references a DataSet, rather than equaling a single ID value. Later, you try to pass EmployeeID to the EmpLeaveDetails method like this:
ds1 = TESTING.EmpLeaveDetails(EmployeeID)
However, the EmpLeaveDetails method takes a String as a parameter. Therefore, you are trying to pass a DataSet into a method that expects a String. Since DataSet objects cannot be automatically converted to the String type, the compiler gives the error.
To fix it, you need to either have the GetEmpID return a string, or else you need to retrieve the single string value from the DataSet before passing it to the EmpLeaveDetails method.

Related

Different output from stored procedure in SSMS and ASP.NET

I created a stored procedure to include a new user for my system. Parameters are: Name, Mail and Password (all varchar). The stored procedure first checks if the mail is already in the database. If not, then the information in added to the table. At the end, the output is a table with the user data.
CREATE PROCEDURE [dbo].[user_new]
(#name VARCHAR(50),
#mail VARCHAR(50),
#password VARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #exist INT
SELECT #exist = COUNT([id])
FROM [dbo].[User]
WHERE [mail] = #mail
IF #exist = 0
INSERT INTO [dbo].[User] ([name], [mail], [password])
VALUES (#name, #mail, #password)
SELECT
#exist AS [exist], [id], [name], [mail]
FROM
[dbo].[User]
WHERE
[mail] = #mail
END
GO
When I execute the stored procedure in SSMS, everything works fine: when I insert a new mail, field [exist] returns 0. When I insert a mail that already exist, field [exist] returns 1. So far, so good.
When I execute the stored procedure from my .NET application (which has a lot of other calls that are working fine), the error happen: no matter if I try to add a new or an existing mail, [exist] always returns 1. I tried to change the logic several times, but I always get the wrong result.
Here is the .NET code:
Public Function api_v2_player_new(<FromBody> s As User) As Object
Dim arrParameters(,) As String = {{"#name", s.Name}, {"#mail", s.Mail}, {"#password", s.Password}}
Dim dtc As Data.DataTableCollection = SQL.Execute("dbo.user_new", arrParameters)
Return SQL.toJson(dtc(0))
End Function
Public Class SQL
Public Shared Function runStoredProcedure(ByVal cmd As SqlCommand) As Data.DataTableCollection
Dim spName As String = cmd.CommandText.ToString
cmd.CommandTimeout = 120
Dim cs As String = System.Configuration.ConfigurationManager.ConnectionStrings("csKickerliga").ConnectionString
Dim connection As SqlConnection = Nothing
connection = New SqlConnection(cs)
Dim dt As DataTable = New DataTable()
cmd.Connection = connection
connection.Open()
Dim adp As New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Return ds.Tables
connection.Close()
End Function
Shared Function Execute(spName As String, arrParameters(,) As String) As Data.DataTableCollection
Dim cmd As SqlCommand = New SqlCommand(spName)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
For i = 0 To (arrParameters.Length / 2) - 1
.AddWithValue(arrParameters(i, 0), arrParameters(i, 1))
Next
End With
Dim dtc = runStoredProcedure(cmd)
Return dtc
End Function
Shared Function toJson(dt As DataTable) As List(Of Object)
Dim oList As New List(Of Object)
Dim o As New Dictionary(Of String, Object)
Dim data As Object
For Each r As DataRow In dt.Rows
o = New Dictionary(Of String, Object)
For Each c As DataColumn In dt.Columns
If IsNumeric(r(c.ColumnName)) Then
If Not r(c.ColumnName).ToString.Contains(".") Then
data = CInt(r(c.ColumnName))
Else
data = r(c.ColumnName).ToString
End If
Else
data = r(c.ColumnName).ToString
End If
o.Add(c.ColumnName, data)
Next
oList.Add(o)
Next
Return oList
End Function
End Class
Found the issue. The code was executing the stored procedure twice:
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Therefore on the recond run the record already existed because it was created on the first run. I removed one of the lines and now it's working!

How to select GUID column by another GUID column in VB.net?My Select query does not work

I am new to programming and get the chance to work and maintain in another developers project.
The project is built with ASP.Net Vb.Net and SQl Server.
I am trying to select the primary key ID (which is actually a GUID) from a table.
SQID = Core.DB.GetString("SELECT id FROM SQC WHERE sid = " & sid)
In the Table SQC the primary key is id which is guid and the sid is also guid which is primary key to another table.
my previous developer developed the code to select string variable GetString function where GetString is
Shared Function GetString(ByVal selectQueryText As String, ByVal ParamArray params As SqlParameter()) As String
Dim dt As DataTable = Nothing
Try
dt = GetData(selectQueryText, CommandType.Text, params)
If dt.Rows.Count = 0 Then
Return ""
Else
If TypeOf dt.Rows(0)(0) Is DBNull Then
Return ""
Else
Return CStr(dt.Rows(0)(0))
End If
End If
Finally
If dt IsNot Nothing Then dt.Dispose()
End Try
End Function
When I debug the code my process enters into GetString Function and from Get String it goes to GetData function
Shared Function GetData(ByVal selectCommandText As String, ByVal selectCommandType As CommandType, ByVal ParamArray params As SqlParameter()) As DataTable
Dim conn As SqlConnection = Nothing
Try
conn = GetOpenSqlConnection()
Return GetData(conn, selectCommandText, selectCommandType, params)
Finally
If conn IsNot Nothing Then conn.Dispose()
End Try
End Function
Shared Function GetData(ByVal conn As SqlConnection, ByVal selectCommandText As String, ByVal selectCommandType As CommandType, ByVal ParamArray params As SqlParameter()) As DataTable
If conn Is Nothing Then Return GetData(selectCommandText, selectCommandType, params)
Dim sa As SqlDataAdapter = Nothing
Try
sa = New SqlDataAdapter(selectCommandText, conn)
sa.SelectCommand.CommandType = selectCommandType
Dim dt As New DataTable
Try
For Each param As SqlParameter In params
sa.SelectCommand.Parameters.Add(param)
Next
sa.Fill(dt)
Return dt
Catch ex As Exception
dt.Dispose()
Throw ex
End Try
Finally
If sa IsNot Nothing Then sa.Dispose()
End Try
End Function
In the Try Catch area of exeption handling the code breaks and throws the exception error. It saying Incorrect syntax near 'a379'. which is first the part of sid (GUID). I mean the sid value is 9417A379-6371-432F-9DA5-BCFC46DD95A1
I am not sure how to handle this. I want to select the id from from SQC table and store it in a variable.
I am looking for your advice and suggestion. As I am new in the programming world please also point me my mistakes.
Thanks
It looks like your issue could be fixed like so:
SQID = Core.DB.GetString("SELECT id FROM SQC WHERE sid = '" & sid & "'")
But you should be aware that this style of code is open to SQL injection and you may want to look at ways of parameterising your queries (i.e. don't take what's in this project as good practice).

Utilize returned value from Stored Procedure using Entity Framework in VB.Net

I hope the below stored procedure inserts a new record to the table and returns the same when executed. I tried to utilize this stored procedure from Entity Framework as shown far below. The new record is properly inserted. But I don't know why I couldn't get the value returned from the procedure.
Stored Procedure:
USE [Materials]
GO
CREATE PROCEDURE [dbo].[insertQuery1]
#Code NVARCHAR(50),
#Name NVARCHAR(100)
AS
BEGIN
INSERT INTO dbo.Materials
(Code, Name)
Values (#Code, #Name)
Select mat.ID, mat.Code, mat.Name from dbo.Materials mat where mat.ID = SCOPE_IDENTITY()
END
ASPX.VB Code:
Protected Sub testing_Click(sender As Object, e As EventArgs)
Dim code As String
Dim name As String
Dim element As Object
code = "New Code"
name = "New Element"
element = ent.insertQuery(code, name)
Dim mat As Material = CType(element, Material)
End Sub
When I try this code, I get the following error
Unable to cast object of type 'System.Data.Objects.ObjectResult`1[Stored_Procedure_Test.insertQuery_Result]' to type 'Stored_Procedure_Test.Material'.
at the line Dim mat As Material = CType(element, Material)
It is very clear from exception that you are casting and object of Stored_Procedure_Test.insertQuery_Result to object type of Material. Your SP returns collection of objects which are of type Stored_Procedure_Test.insertQuery_Result. So what you can do is get value from the object returned by SP like this.
Stored_Procedure_Test.insertQuery_Result element = ent.insertQuery(code, name).FirstOrDefault();
//And you can access properties of this object like this
string name=element.Name;
So your complete code should look like this
Protected Sub testing_Click(sender As Object, e As EventArgs)
Dim code As String
Dim name As String
code = "New Code"
name = "New Element"
Dim element As Stored_Procedure_Test.insertQuery_Result = ent.insertQuery(code, name).FirstOrDefault();
//Now you can directly use the `element` to access values returned from SP.
End Sub

data type mismatch in criteria expression vb.net access

This My Code
Public Function simpan() As Integer
Dim sql As String
Dim cmmd As OleDbCommand
sql = "INSERT INTO disposisi (nodisposisi,noagendamasuk,idseksi,intruksi,tgldisposisi,nosurat,perihal,nama)" & _
"values(?,?,?,?,?,?,?,?)"
cmmd = New OleDbCommand(sql, cnn)
cmmd.CommandType = CommandType.Text
cmmd.Parameters.AddWithValue("nodisposisi", FNoDisposisi)
cmmd.Parameters.AddWithValue("noagendamasuk", FAgenda)
cmmd.Parameters.AddWithValue("idseksi", FIdSeksi)
cmmd.Parameters.AddWithValue("intruksi", FIntruksi)
cmmd.Parameters.AddWithValue("tgldisposisi", FTgl)
cmmd.Parameters.AddWithValue("nosurat", FNoSrt)
cmmd.Parameters.AddWithValue("perihal", FPerihal)
cmmd.Parameters.AddWithValue("nama", FNama)
Return cmmd.ExecuteNonQuery()
End Function
I don't know what i do please help me
probably the data type you are trying to insert in table is not what that column is expecting
like you are inserting char in int column .you need to check table definition.You have to
look at the Databases's expected datatype to know for sure

How to get output parameter of sql in codebehind

My stored procedure is like this.
ALTER PROCEDURE [dbo].[GetImagesByDesignId]
#DesignID bigint,
#RegID bigint,
#PageIndex INT,
#NumRows INT,
#ImageCount INT OUTPUT
AS
BEGIN
SELECT #ImageCount=(SELECT COUNT(*) FROM DocManagement where DesignID=#DesignID and RegID=#RegID)
Declare #startRowIndex INT;
set #startRowIndex = (#PageIndex * #NumRows) + 1;
With ImageEntries as (
SELECT ROW_NUMBER() OVER (ORDER BY DocumentID ASC) as Row, RegID, DesignID,ImageName
FROM DocManagement
WHERE DesignID=#DesignID and RegID=#RegID
)
Select RegID, DesignID,ImageName
FROM ImageEntries
WHERE Row between
#startRowIndex and #StartRowIndex+#NumRows-1
END
I am calling storedprocedure in my codebehind as
Dim dt As DataTable = objUpload.GetDocuments(lngRegID, lngDesignID)
dlView.DataSource = dt
dlView.DataBind()
dlView is datalist.Method GetDocuments is written in another class like this
Public Function GetDocuments(ByVal lngRegID As Long, ByVal lngDesID As Long) As DataTable
Try
Dim db As Database = DatabaseFactory.CreateDatabase()
Dim DbCommand As DbCommand = db.GetStoredProcCommand("GetImagesByDesignId")
db.AddInParameter(DbCommand, "#RegID", DbType.Int64, lngRegID)
db.AddInParameter(DbCommand, "#DesignID", DbType.Int64, lngDesID)
db.AddInParameter(DbCommand, "#PageIndex ", DbType.Int32, intPageIndex)
db.AddInParameter(DbCommand, "#NumRows ", DbType.Int32, intNumRows)
db.AddOutParameter(DbCommand, "ImageCount", DbType.Int32, 250)
Return db.ExecuteDataSet(DbCommand).Tables(0)
Dim strOutput() As String = {db.GetParameterValue(DbCommand, "ImageCount").ToString}
Catch ex As Exception
End Try
End Function
Problem is i want to get datattable as well as imagecount in codebehind.How can i return back datatable and imagecount to codebehind.Can anybody help?
You can create a class to use are return value that holds both the data table and the image count. Or you can send a variable as an argument by reference:
Public Function GetDocuments(ByVal regID As Long, ByVal desID As Long, ByRef imageCount As Integer) As DataTable
In the method you just set the value of imageCount.
In your stored procedure you don't need a nested query to get the count. Just do like this:
select #ImageCount = count(*)
from DocManagement
where DesignID = #DesignID and RegID = #RegID
Note:
I see that you have a Catch block without anything in it. Never ever do that. You are catching exceptions and ignoring them, that can only lead to problems.
In there rare case where you actually need to catch an exception and ignore it, you should at least have a comment inside the Catch block explaining why it's ignored.
Also, you are catching the base class Exception, when you should catch a more specific class like SqlException.
Public Function GetDocuments(ByVal lngRegID As Long, ByVal lngDesID As Long, ByRef strOutput As String) As DataTable
You can use ByRef and pass a string variable as a reference and set it in your method. The reference of strOutput will be passed to your method, and when you set the value of that variable in the method you can get back the changed value after the method call.
Dim strOutput As String = Nothing
Dim dt As DataTable = GetDocuments(lngRegID, lngDesID, strOutput)
Console.WriteLine(strOutput)

Resources