MySQL Output parameter with asp.net and SqlDataSource control - asp.net

I'm in the process of switching my application from MSSQL to MYSQL. When I was using MSSQL, I retrieved the last auto increment value via
Private Sub dsImpoundInformation_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsImpoundInformation.Inserted
_impoundId = e.Command.Parameters("impoundId").Value
End Sub
Private Sub dsImpoundInformation_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles dsImpoundInformation.Inserting
Dim impoundIdparam As New SqlClient.SqlParameter()
impoundIdparam.ParameterName = "impoundId"
impoundIdparam.Direction = System.Data.ParameterDirection.Output
impoundIdparam.DbType = DbType.Int32
impoundIdparam.Value = 0
e.Command.Parameters.Add(impoundIdparam)
End Sub
and
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET #impoundId = SCOPE_IDENTITY();"
Now when i try
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET #impoundId = LAST_INSERT_ID();"
i get the error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '0 = LAST_INSERT_ID()' at line 1
And when i try:
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET impoundId = LAST_INSERT_ID();"
I get the error:
Unknown system variable 'impoundId'
ultimately, I'm just trying to get the last auto increment value but there are other sections of my code in other applications that I plan on switching to MYSQL that depend on output parameters. I have't yet explored using stored procedures but at this time I would like to get this to work in a similar fashion to how I had it with MSSQL.
Thanks in advance.

Finally I broke down and decided to use stored procedures. This is the best way to do it any ways and makes the code a lot cleaner. For anyone that's encountering this same problem my advice to you would be don't waste you time trying to make it work and just use a stored procedure.

Related

Error when using the WHERE clause in Linq-to-SQL

I have a datacontext that I'm trying to query, the results of which I want to bind to a gridview on a button click. Getting connected to the datacontext works great. I get the 1000s of records I expect. When I try to add the WHERE clause, I run into problems. Here's the button event I'm trying to make it happen at:
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim dsource = New MY_DataContext().SV_XXXs '--- This works, the data is all there
gridRec.DataSource = dsource.ToList().Where(Function(dtable) dtable.PN = Session("PN")) '--- this fails
'--- Also tried this, it also did not work ----------------------------------------------------------
'--- gridRec.DataSource = dsource.Where(Function(dtable) dtable.PN = Session("PN")) '--- this fails
'----------------------------------------------------------------------------------------------------
gridRec.DataBind()
End Sub
The session variable is valid and the dsource is populating correctly, but I get the following error when it tries to execute the Where clause:
Evaluation of method
System.Linq.SystemCore_EnumerableDebugView`1[SV_REC].get_Items() calls
into native method System.WeakReference.get_Target(). Evaluation of
native methods in this context is not supported.
Also tried:
Dim results =
(
From T In dsource
Where T.PN = Session("SAFRReceiverPN")
Select T
).ToList
And get this error
Method 'System.Object CompareObjectEqual(System.Object, System.Object,
Boolean)' has no supported translation to SQL.
And tried:
Dim results = From t In dsource Where (t.PN = Session("SAFRReceiverPN")) Select t
nothing seems to work for me when trying a WHERE clause
C# or VB.NET are both cool if you have any suggestions.
Really, any help is appreciated, thanks.
LINQ to SQL doesn't know what to do when you try to access the session inside the query. Instead of doing that, fetch the value from the session before the query and store the result in a local variable, then use that local variable in your query. For example, in C#:
var receiver = (string) Session["SAFRReceiverPN"];
var results = dsource.Where(t => t.PN == receiver);
(I don't bother with query expressions when you're just trying to perform a simple filter.)

Select Query on Access Database in Visual Studio

heres my code :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
ltRooms.Text = CInt(Session("numOfRooms"))
'Calculate total cost
Dim intPrice As Integer
Dim intTotal As Integer
intPrice = AccessDataSource1.SelectCommand = "SELECT [Price] FROM [Rooms] WHERE ([RoomType] = 'RoomType')"
intTotal = intPrice * intRooms
ltPrice.Text = intTotal.ToString
End Sub
and my datasource
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="Hostel.accdb"
SelectCommand="SELECT * FROM [Bookings]"></asp:AccessDataSource>
I'm trying to store the value from the select query and then use it to work out the total price and then store it in a literal. So far I am only getting 0. No compile errors.
Does anyone one know why this isn't working?
I am consolidating the various comments into an answer for clarity and to stop the page complaining about extended discussion. This is all off the top of my head so there might be some errors in the code. It should be enough to pinpoint the problem though.
Firstly, now that I look at it again today, I think your code is just setting the SelectCommand property of the data source and not actually querying the database. I think you need to use the DataSource.Select method.
Your code might end up looking something like this:
AccessDataSource1.SelectCommand = "SELECT [Price] FROM [Rooms] WHERE ([RoomType] = '" & RoomType & "')"
Dim intPrices As List(Of Integer) = AccessDataSource1.Select(DataSourceSelectArguments.Empty)
' Now do stuff with your price data.
If the above doesn't help then I would check the value of intPrice returned by the Select call. You should also check that RoomType is set correctly.
If the wrong data is coming back from the database then you should be able to fix your SQL query to retrieve the correct data. If you need further assistance with this then please post the SQL query and the table structure.
If the correct data is coming back then check where intRooms is defined. If it is zero then your total will be calculated as zero regardless of the value of intPrice.

.Net: code for BtnLock_Click

I have been trying to apply a solution to some functionality that a user requires on their system.
A user requires me to implement a locking system on their system. They have multiple users which may require to access the site, but the user would like the ability for them to independently lock a records in the web site site, for them to add notes to and to then unlock this so other users are able to do the same.
I have a button on my web page simply named btnLock and i have added an additional column in my database called LockedBy and have the following stored procedure...
ALTER PROCEDURE LockWeeklyTest
(
#AgendaID BIGINT,
#LockingUser VARCHAR(20)
)
AS
BEGIN
SET NOCOUNT ON
UPDATE
WeeklyAgenda
SET
LockedBy = #LockingUser
WHERE
AgendaID = #AgendaID
AND
LockedBy IS NULL
END
I have a class named Weekly Class and have the following code...
Public Shared Sub LockWeeklyAgenda(ByVal WeeklyClass As WeeklyClass)
Using dbConnection As New SqlConnection(ConfigurationManager.AppSettings("dbConnection"))
dbConnection.Open()
Dim dbTrans As SqlTransaction
dbTrans = dbConnection.BeginTransaction()
Using dbCommand As SqlCommand = dbConnection.CreateCommand
With dbCommand
.Transaction = dbTrans
.CommandType = CommandType.StoredProcedure
.CommandText = "LockWeeklyTest"
'Add Parameters for Update
.Parameters.AddWithValue("#AgendaID", WeeklyClass.AgendaID)
.Parameters.AddWithValue("#LockingUser", WeeklyClass.LockedBy)
dbCommand.ExecuteNonQuery()
End With
End Using 'dbCommand
dbTrans.Commit()
End Using
End Sub
I was thinking that the below code for the butlock would populate my Loggedby field with the username but this isnt the case.
Protected Sub btnLock_Click(sender As Object, e As System.EventArgs) Handles btnLock.Click
Dim lock As New WeeklyClass
If lock.LockedBy = "Null" Then
lock.LockedBy = System.Environment.UserName
'lock.AgendaID = AgendaID
End If
' save to the database using the Class DAL
WeeklyClassDAL.LockWeeklyAgenda(lock)
End Sub
I know that the Stored Procedure works as i have tested with the following statement as an example...
EXEC LockWeeklyTest 11, 'Betty'
Im sure that its something to do with the btnlock_click, but im not 100% sure what this is.
Any help is much appriechiated.
Your problem is this line:
If lock.LockedBy = "Null" Then
"Null" is actually a string containing the word Null. What you're after is:
If String.IsNullOrEmpty(lock.LockedBy) Then
That way, if it is actually null or empty, your LockedBy will be set. Currently, it's only setting the LockedBy if LockedBy already equals the string value "Null", which it won't directly after being declared. Is this logic really necessary considering LockedBy will always be null directly after you've declared the WeeklyClass?
Something doesn't look quite right with the AgendaID:
During the button click event the value has been commented out but is still passed through to the stored procedure inside the data layer's 'LockWeeklyAgenda' method.
It's also not defined as a nullable parameter inside the stored procedure itself, so the value that's being sent would depend on the WeeklyClass class' constructor..
can you please also show how the WeeklyClass code looks like?

Identity of recently added record and insert from gridview?

I am developing an ASP.Net VB Web Application
The application contains a GridView which displays the records of a user table from my created datable. The database is an Sql server database.
The code below inserts data into one table and through the built in function ##Identity to insert the most recently added record id (tt_id) from the trainingTbl table and inserting that record id into the userAssessmentTbl. Adding the identity to the second userAssessmentTbl table works fine.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lblUsr2 As Control = FindControlRecursive(MultiTabs, "txtUsr")
Dim strQuery As String
Dim cmd As SqlCommand
strQuery = "Insert into trainingTbl(s_id, t_date, EditorId, wa_id, st_id) values(#s_id , #t_date, #EditorId, #wa_id, #st_id ) Insert into userAssessmentTbl(tt_id, UserId) values(##Identity, #UserId)"
cmd = New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#s_id", DDLCourse.Text)
cmd.Parameters.AddWithValue("#t_date", Convert.ToDateTime(txtDate.Text))
cmd.Parameters.AddWithValue("#EditorId", User.Identity.Name.ToString())
cmd.Parameters.AddWithValue("#st_id", myLblStation.Value().ToString)
cmd.Parameters.AddWithValue("#wa_id", myLblWatch.Value().ToString)
cmd.Parameters.AddWithValue("#UserId", lblUsr2.UniqueID.ToString)
InsertUpdateData(cmd)
End Sub
The issue I’m having seems to be centered on how I insert a uniqueidenifier from a GridView into a userAssessmentTbl database!
And how, I guess using a loop I can insert the UserId records from that Gridview (GridView1) into the userAssessmentTbl table along with the looped id from the ##Identity.
This part of the insert parameter seems to be incorrect:
cmd.Parameters.AddWithValue("#UserId", lblUsr2.UniqueID().ToString)
And the error I’m met with is: 'Conversion failed when converting from a character string to uniqueidentifier.'
I’ve also tried it like this:
cmd.Parameters.AddWithValue("#UserId", SqlDbType.UniqueIdentifier).Value().ToString()
And im met with the error: 'Operand type clash: int is incompatible with uniqueidentifier'
The qusetion has slightly changed to how do I Insert a String into SQL DB Where DataType Is Uniqueidentifier?
Any help will be really appreciated.
Well first of all:
##IDENTITY returns the most recently created identity for your current
connection, not necessarily the identity for the recently added row in
a table. Always use SCOPE_IDENTITY() to return the identity of the
recently added row.
Secondly, to asnwer your question:
The SQL type Uniqueidentifier and the CLR type Guid match up.
So instead of passing "#UserId" in as a parameter you need to create a Guid out of the string value.
Dim userID As Guid = New Guid(lblUsr2.UniqueID.ToString)

ADO error "Current Recordset does not support updating. This may be a limitation of the provider, or of the selected locktype."

I am doing some calculation with the data set I take from my database. Null values give errors so I tried replacing null values with zeros(0). Here is the error I get,
ADODB.Recordset error '800a0cb3'
Current Recordset does not support
updating. This may be a limitation of
the provider, or of the selected
locktype.
Never seen it before. Here is my code.
If IsNull(objRevenueToday("REVENUE")) Then
objRevenueToday("REVENUE") = 0
End If
Your recordset appears to be read-only. There could be a number of reasons for this; you're reading a view that contains a Group By clause, you don't have permissions, etc.
Using the syntax Set Recordset = Command.Execute always opens a read only cursor. What you need to do is open the cursor using the Recordset object. The Source parameter of the Open method is your Command object. This allows you to set the desired location and locktype.
Dim cmdProc as ADODB.Command
Dim rsData as ADODB.Recordset
Set cmdProc = New ADODB.Command
With cmdProc
Set .ActiveConnection = SomeConnection
.CommandType = adCmdStoredProc
.CommandText = "selCustomer"
' ... Create parameters
End With
Set rsData as New ADODB.Recordset
rsData.Open cmdProc,, adOpenStatic,adLockBatchOptimistic
'...Process recordset data.
Here is the solution:
If IsNull(objRevenueToday("REVENUE")) Then
RevenueToday = "0"
Else
RevenueToday = objRevenueToday("REVENUE")
End If
Not very ideal but fixed my error.
Assuming SQL Server (although similar techniques available in other DBs.
Change the query so that is will not return nulls in records. For example in the T-SQL
SELECT ISNULL(REVENUE, 0), .... FROM ....
Change the settings as below. It force the client side cursor...It worked for me
set pagedlistrs=CreateObject("adodb.recordset")
pagedlistrs.cursorlocation = 3 ' adUseClientpagedlistrs
pagedlistrs.Open SQL, objConn, 3,3,1

Resources