Identity of recently added record and insert from gridview? - asp.net

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)

Related

Cant pass null values to SqlServer from VB.net?

Im using VB.net to control a DevExpress report object, i currently have a function that handles the data of said report, and when i run it the reports data comes back completely blank. When i run SQL Server Profiler i can see the command exec dbo.sp_Get_CompanyTime #intCompanyID=1,#dteStart=NULL,#dteEnd=NULL,#strUserID=N'',#intCustomerID=1,#intProjectID=1 is ran when the report is called, returning no data at all because there UserID doesnt match anything, same for customer ID and project ID. The problem im facing is that in VB i have
Dim spcomptime As dsReporting.sp_Get_CompanyTimeDataTable = New dsReporting.sp_Get_CompanyTimeDataTable
Dim OpenDate As Nullable(Of DateTime)
Dim CloseDate As Nullable(Of DateTime)
Dim clientId As Nullable(Of Integer)
Dim cusId As Nullable(Of Integer)
Dim proID As Nullable(Of Integer)
Sp_Get_CompanyTimeTableAdapter.Fill(spcomptime, 1, OpenDate, CloseDate, clientId, cusId, proID)
which as you can hopefully see it should be passing null values for everything past the first 2 parameters! ive tried using DBNull.value as suggested elsewhere, but it tells me it cannot be converted to type "Integer?".
Somebody help me i've been trying to solve this for what feels like an age.

User details stored in separate table ASP.NET Identity

I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...

Checking if there is an exception coming from the server

I have an ASP.NET web application written in vb.net. I have uploaded the application on a web server in the wwroot folder and once I type in the URL with a QueryString, on page_Load it should request that QueryString and store it in the database once in Table1 and another in Table2. Well it is inserting the QueryString to Table 1 but not to Table2. The insertion code is within a Try Catch block but the problem is that I have no idea how to display a server MsgBox with the exception on the client-side.
I have also tried writing a txtFile containing any ex.message on the WebServer itself, but with no luck, even without an exception firing, the txtFile is not created I guess its a path issue. Whether to write the physical path or virtual path both tested without luck.
I am really desperate to know in anyway possible why its inserting the QueryString to Table1 and not Table2.
I am using a class.vb to insert the Querystring. On the main page, I request the QueryString which is a variable (changing) table name (Table2), pass it to a function defined in class.vb and then apply an Insert statement for a predefined un-changing table (Table1) and also using the retrieved QueryString (Table2) name to insert a date and time to both tables.
On MainPage.aspx:
Dim classOBJ AS new Projet.class1
classOBJ.Fun(Request.QueryString("Table"))
In Class1.vb:
Public Sub Fun(ByVal value As String)
Dim date_T As Date = Date.Today
Try
Using myconn As New SqlConnection(ConnString)
myconn.Open()
Dim cmd1 = New SqlCommand("INSERT INTO Table1 (Date_T,Time_T) values (#paramdate, #paramtime)", myconn)
cmd1.Parameters.AddWithValue("#paramdate", date_T)
cmd1.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim cmd2 = New SqlCommand("Insert into [" & value & "] (Date_T, Time_T) values (#paramdate, #paramtime)", myconn)
cmd2.Parameters.AddWithValue("#paramdate", date_T)
cmd2.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd2.ExecuteNonQuery()
cmd2.Dispose()
myconn.Close()
End Using
I am using this notation [ ] because Table's 2 name is a number.

.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?

MySQL Output parameter with asp.net and SqlDataSource control

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.

Resources