Using VariantType in ASP.net - asp.net

Hoping for a quick answer here.
OK, since I do a lot of single value lookups from the DB, I created a function to handle the lookup for me. It's designed to get any type of data type (string, integer, date, ...).
It works when I want to retrieve a number, but gives me an error when I want a string (InvalidCastException trying to convert a string to an integer on the line: GetValue = DR(0)).
I can't do a ctype or directcast because the datatype is unknown and varies.
Haven't tested any other data types yet.
Code is below. I'd like to find out how to make this function work, or pointed to another function that will serve the same purpose.
Public Shared Function GetValue(Optional ByVal SQL As String = "", Optional ByVal FieldName As String = "", Optional ByVal TableName As String = "", Optional ByVal WhereClause As String = "") As VariantType?
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim strSQL As New SQLStringBuilder
Dim DR As SqlDataReader
myConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnAFRAMSSQL").ConnectionString)
strSQL.Add(SQL)
If FieldName > "" Then
strSQL.Add("SELECT " & FieldName)
End If
If TableName > "" Then
strSQL.Add("FROM " & TableName)
End If
If WhereClause > "" Then
strSQL.Add("WHERE " & WhereClause)
End If
myConnection.Open()
myCommand = New SqlCommand(strSQL.ToString, myConnection)
DR = myCommand.ExecuteReader()
If DR.HasRows Then
DR.Read()
GetValue = DR(0)
Else
GetValue = Nothing
End If
End Function
Thanks.

You may specify the System.Object (System.Object is the ultimate base class of all types) return type of your method.
Public Shared Function GetValue(Optional ByVal SQL As String = "", Optional ByVal FieldName As String = "", Optional ByVal TableName As String = "", Optional ByVal WhereClause As String = "") As Object
Dim myConnection As SqlConnection
....
Dim obj as Object=Nothing
If DR.Read()
obj=DR(0)
End If
DR.Close()
myConnection.Close()
return obj
End Function

Related

Duplicate records created on page load vb.net

I trying to figure out why my code in inserting two records into the database when it executes? the CreateEnrollment Sub executes fine, however the results insert 2 sometimes 3 records ranging from 1-10 seconds apart, depending on remote server load. I first thought it might be the IsPostBack problem but adding the If Not Page.IsPostBack Then did not resolve.
Dim FailedMessage As String = "This COPDI (On-Line) user failed: "
Dim PassedMessage As String = "This COPDI (On-Line) user passes: "
Dim ClassName As String = "COPDI (FAILED)"
Dim SendMailAddress As String = "myEmailAddress.com"
Dim SubsiteConnString As String = "Subsite_appSettings"
Dim MainsiteConnString As String = "SubsiteConn"
Dim RecordsReturned As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim UserName As String = User.Identity.Name()
Dim userID As Integer = GetUID(UserName)
Dim ClassDate As Date = DateTime.Now.AddHours(3).ToShortDateString
Dim ClassTime As String = DateTime.Now.AddHours(3). ToShortTimeString
If Not Page.IsPostBack Then
If Request.QueryString("code") = 1111 Then
RecordsReturned = RecordExist(UserName)
CreateEnrollment(UserName, ClassDate, ClassTime, ClassName, userID)
UpdateLastActivityDate(UserName)
If RecordsReturned < 3 Then
Response.Redirect("~/transcript.aspx" & "?code=" & RecordsReturned)
Else
Response.Redirect("~/transcript.aspx" & "?code=" & "more_than_three")
End If
End If
End If
End Sub
Public Sub CreateEnrollment(ByVal UserName As String, ByVal ClassDate As Date, ByVal ClassTime As String, ByVal ClassName As String, ByVal UID As Integer)
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = "INSERT INTO EnrollmentsTbl (" & _
"[UserName],[SubmitTime],[ClassTime],[ClassDate],[Enrolled],[ClassName],[Instructor],[DateCompleted],[Completed],[WaitListed],[UID]) " & _
"VALUES (#UserName, #SubmitTime, #ClassTime, #ClassDate, #Enrolled, #ClassName, #Instructor, #DateCompleted, #Completed, #WaitListed, #UID) "
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("#UserName", UserName)
comm.Parameters.AddWithValue("#SubmitTime", DateTime.Now.AddHours(3).ToString())
comm.Parameters.AddWithValue("#ClassTime", ClassTime)
comm.Parameters.AddWithValue("#ClassDate", ClassDate)
comm.Parameters.AddWithValue("#Enrolled", True)
comm.Parameters.AddWithValue("#ClassName", ClassName)
comm.Parameters.AddWithValue("#Instructor", "On-line")
comm.Parameters.AddWithValue("#DateCompleted", DateTime.Now.AddHours(3).ToString)
comm.Parameters.AddWithValue("#Completed", False)
comm.Parameters.AddWithValue("#WaitListed", False)
comm.Parameters.AddWithValue("#UID", UID)
Dim result As Integer = comm.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Sub
Public Function RecordExist(ByVal username As String) As Integer
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Dim sql As String = "SELECT COUNT(*) FROM EnrollmentsTbl " & _
"WHERE [UserName] = """ & username & """ AND ClassName LIKE """ & ClassName & """ AND [Completed] = 0 AND [Enrolled] = -1"
Dim DBCommand As New Data.OleDb.OleDbCommand(sql, conn)
Try
conn.Open()
Dim RecordCount As Integer = CInt(DBCommand.ExecuteScalar())
conn.Close()
Return RecordCount
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Function
Public Function GetUID(ByVal username As String) As Integer
Dim xUserName As String = User.Identity.Name()
If (Not xUserName="") Then
Dim objConn As Data.OleDb.OleDbConnection
Dim objCmd As Data.OleDb.OleDbCommand
Dim objRdr As Data.OleDb.OleDbDataReader
Dim userAN As String
Dim strConnection As String = ConfigurationManager.ConnectionStrings("TechTrainingConn").ToString
objConn = New Data.OleDb.OleDbConnection(strConnection)
objCmd = New Data.OleDb.OleDbCommand("SELECT * FROM UsersDataTbl WHERE [UserName] = """ & xUserName & """", objConn)
Try
objConn.Open()
objRdr = objCmd.ExecuteReader()
While objRdr.Read()
userAN = objRdr.Item("UID")
End While
objRdr.Close()
objConn.Close()
Session("userID") = userAN
Return userAN
'Response.Write(Session("userAN") & " - " & xUserName)
Catch ex As Exception
Response.Write(ex)
Finally
objConn.Close()
End Try
End If
End Function
What aspx page is this supporting? I noticed you have a redirect to transcript.aspx, is this code for that page? If so that would explain the multiple page loads. Response.Redirect is not a postback so it's going to fall into recordReturned and CreateEnrollment methods again, especially if you are passing the &code=1111 in the URL querystring

Get each key value out of a dictionary of strings object without using newsoft json

I have an indexpage.aspx which I post data into on page load. In this page I created list of strings
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim openWith As New SortedList(Of String, String)
' Add some elements to the list. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("version", "1")
openWith.Add("key", ConfigurationManager.AppSettings("publickey"))
openWith.Add("cmd", "get_callback_address")
openWith.Add("currency", "coin")
Call POSTAPI("get_callback_address", openWith)
End Sub
Now I have a payment class which has postapi function, here's the class
Public Shared Function POSTAPI(cmd As String, Optional parms As SortedList(Of String, String) = Nothing) As Dictionary(Of String, Object)
Dim post_data As String = ""
For Each parm As KeyValuePair(Of String, String) In parms
If post_data.Length > 0 Then
post_data += "&"
End If
post_data += parm.Key + "=" + Uri.EscapeDataString(parm.Value)
Next
Dim keyBytes As Byte() = encoding.GetBytes(s_privkey)
Dim postBytes As Byte() = encoding.GetBytes(post_data)
Dim hmacsha512 = New System.Security.Cryptography.HMACSHA512(keyBytes)
Dim hmac As String = BitConverter.ToString(hmacsha512.ComputeHash(postBytes)).Replace("-", String.Empty)
' do the post:
Dim cl As New System.Net.WebClient()
cl.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
cl.Headers.Add("HMAC", hmac)
cl.Encoding = encoding
Dim ret = New Dictionary(Of String, Object)()
Try
Dim resp As String = cl.UploadString("https://www.coinpayments.net/api.php", post_data)
Dim decoder = New System.Web.Script.Serialization.JavaScriptSerializer()
ret = decoder.Deserialize(Of Dictionary(Of String, Object))(resp)
Catch e As System.Net.WebException
ret("error") = "Exception while contacting CoinPayments.net: " + e.Message
Catch e As Exception
ret("error") = "Unknown exception: " + e.Message
End Try
Return ret
End Function
Its posting successfully but A successful call to the 'get_callback_address' or 'get_deposit_address' command will give you a result similar to this (JSON):
{
"error":"ok",
"result":{
"address":"1BitcoinAddress",
"pubkey":"",
"dest_tag":100,
}
}
Above are the keys and values is returning. Now my question is I only want to get the values of result and split it so it gives me "1BitcoinAddress", "pubkey" and save it to my database(I want to get the 3 values of that resultkey so i can save it in my database".
Thank you.
Since you deserialized the incoming json as a Dictionary(Of String, Object) the JavaScriptSerializer should have already created a second dictionary for the value of the result key. The only thing you have to do now, is create a variable that takes the value stored in the dictionary and cast it as a Dictionary(Of String, Object) in order to use it, like in this example
Dim json As String = "{" +
"""error"":""ok""," +
"""result"":{" +
"""address"":""1BitcoinAddress""," +
"""pubkey"":""""," +
"""dest_tag"":100" +
"}" +
"}"
Dim deserializer = New System.Web.Script.Serialization.JavaScriptSerializer()
'get the full dictionary
Dim dictionary = deserializer.Deserialize(Of Dictionary(Of String, Object))(json)
' make sure there is a key in your dictionary
If dictionary.ContainsKey("result") Then
'cast the value for "result" as a dictionary
Dim resultDictionary As Dictionary(Of String, Object) = _
DirectCast(dictionary("result"), Dictionary(Of String, Object))
'you can then access the keys by their key
Console.WriteLine("address: {0}, pubkey: {1}, dest_tag: {2}", _
resultDictionary("address"), _
resultDictionary("pubkey"), _
resultDictionary("dest_tag"))
End If
With your input, the program gives an output on the console, like this:
address: 1BitcoinAddress, pubkey: , dest_tag: 100
The big question of your question is really why you want to solve the deserialization without the use of Json.net. On the website for the JavaScriptSerializer,
it says at once:
Json.NET should be used serialization and deserialization. Provides serialization and deserialization functionality for AJAX-enabled applications.

Augmenting membership user creation functionality

As its well known that membership create user functionality lacks a lot of user details that someone might need to store. I am presenting my work around it and I need your expert opinion, ( I am using web method)
I m currently using this code (Ref Microsoft)
Public Function GetErrorMessage(status As MembershipCreateStatus) As String
Select Case status
Case MembershipCreateStatus.DuplicateUserName
Return "Username already exists. Please enter a different user name."
Case MembershipCreateStatus.DuplicateEmail
Return "A username for that e-mail address already exists. Please enter a different e-mail address."
Case MembershipCreateStatus.InvalidPassword
Return "The password provided is invalid. Please enter a valid password value."
Case MembershipCreateStatus.InvalidEmail
Return "The e-mail address provided is invalid. Please check the value and try again."
Case MembershipCreateStatus.InvalidAnswer
Return "The password retrieval answer provided is invalid. Please check the value and try again."
Case MembershipCreateStatus.InvalidQuestion
Return "The password retrieval question provided is invalid. Please check the value and try again."
Case MembershipCreateStatus.InvalidUserName
Return "The user name provided is invalid. Please check the value and try again."
Case MembershipCreateStatus.ProviderError
Return "The authentication provider Returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."
Case MembershipCreateStatus.UserRejected
Return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."
Case Else
Return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."
End Select
End Function
Public Function GetUsrID(UserName) As String
Dim sql As String = "SELECT UserId FROM aspnet_Users WHERE UserName= #UserName"
Using cn As New SqlConnection(ARTSQLDBCOM), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#UserName", SqlDbType.VarChar, 256).Value = UserName
cn.Open()
Dim val As String = String.Empty
Dim getVal As Object = cmd.ExecuteScalar()
cn.Close()
If Not IsNothing(getVal) Then
val = getVal.ToString
Return val
Else
Return Nothing
End If
End Using
End Function
Public Function CreateUser_AugmentedUpdate(ByVal UserName As String, ByVal JobTitleID As String, ByVal Prfx As String, ByVal fname As String, ByVal Mname As String, ByVal Lname As String, ByVal Initial As String, _
ByVal disname As String, ByVal UsrDOB As String, ByVal TelNum As String, ByVal UsrSignature As String, ByVal UsrImg_aURL As String, ByVal UsrImg_rURL As String)
Try
Dim UserID As String = GetUsrID(UserName)
Dim SQLCmd As New SqlCommand()
SQLCmd.CommandType = CommandType.StoredProcedure
SQLCmd.CommandText = "aspnet_Users_CreateUser_AugmentedUpdate"
SQLCmd.Parameters.Add("#UserId", SqlDbType.NVarChar).Value = UserID.ToString
If (String.IsNullOrEmpty(JobTitleID)) Then
SQLCmd.Parameters.Add("#JobTitleID", SqlDbType.Int).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#JobTitleID", SqlDbType.Int).Value = Convert.ToInt32(JobTitleID)
End If
If (String.IsNullOrEmpty(Initial)) Then
SQLCmd.Parameters.Add("#Initial", SqlDbType.Int).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#Initial", SqlDbType.Int).Value = Convert.ToInt32(Initial)
End If
If (String.IsNullOrEmpty(Prfx)) Then
SQLCmd.Parameters.Add("#Prfx", SqlDbType.Int).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#Prfx", SqlDbType.Int).Value = Convert.ToInt32(Prfx)
End If
If (String.IsNullOrEmpty(fname)) Then
SQLCmd.Parameters.Add("#fname", SqlDbType.NVarChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#fname", SqlDbType.NVarChar).Value = fname.ToString
End If
If (String.IsNullOrEmpty(Mname)) Then
SQLCmd.Parameters.Add("#Mname", SqlDbType.NVarChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#Mname", SqlDbType.NVarChar).Value = Mname.ToString
End If
If (String.IsNullOrEmpty(Lname)) Then
SQLCmd.Parameters.Add("#Lname", SqlDbType.NVarChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#Lname", SqlDbType.NVarChar).Value = Lname.ToString
End If
If (String.IsNullOrEmpty(disname)) Then
SQLCmd.Parameters.Add("#disname", SqlDbType.NVarChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#disname", SqlDbType.NVarChar).Value = disname.ToString
End If
Dim dateValue As Date
If String.IsNullOrWhiteSpace(UsrDOB) Then
SQLCmd.Parameters.Add("#UsrDOB", SqlDbType.Date).Value = DBNull.Value
ElseIf Date.TryParse(UsrDOB, dateValue) Then
SQLCmd.Parameters.Add("#UsrDOB", SqlDbType.Date).Value = dateValue
Else
SQLCmd.Parameters.Add("#UsrDOB", SqlDbType.Date).Value = DBNull.Value
End If
If (String.IsNullOrEmpty(TelNum)) Then
SQLCmd.Parameters.Add("#TelNum", SqlDbType.NChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#TelNum", SqlDbType.NChar).Value = TelNum.ToString
End If
If (String.IsNullOrEmpty(UsrSignature)) Then
SQLCmd.Parameters.Add("#UsrSignature", SqlDbType.NVarChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#UsrSignature", SqlDbType.NVarChar).Value = UsrSignature.ToString
End If
If (String.IsNullOrEmpty(UsrImg_aURL)) Then
SQLCmd.Parameters.Add("#UsrImg_aURL", SqlDbType.NVarChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#UsrImg_aURL", SqlDbType.NVarChar).Value = UsrImg_aURL.ToString
End If
If (String.IsNullOrEmpty(UsrImg_rURL)) Then
SQLCmd.Parameters.Add("#UsrImg_rURL", SqlDbType.NVarChar).Value = DBNull.Value
Else
SQLCmd.Parameters.Add("#UsrImg_rURL", SqlDbType.NVarChar).Value = UsrImg_rURL.ToString
End If
SQLCmd.Connection = ARTSQLCON
ARTSQLCON.Open()
SQLCmd.ExecuteNonQuery()
ARTSQLCON.Close()
Return "User has been Created Successfully"
Catch
Return "Create User Phase 2 Error. Please refer to your database developer"
End Try
End Function
<WebMethod()> _
Public Function RegNewUser(ByVal Username As String, ByVal Password As String, ByVal Email As String, ByVal JobTitleID As String, ByVal Prfx As String, ByVal fname As String, ByVal Mname As String, ByVal Lname As String, ByVal Initial As String, _
ByVal disname As String, ByVal UsrDOB As String, ByVal TelNum As String, ByVal UsrSignature As String, ByVal UsrImg_aURL As String, ByVal UsrImg_rURL As String) As String
Dim status As MembershipCreateStatus
'Dim passwordQuestion As String = ""
'Dim passwordAnswer As String = ""
'If Membership.RequiresQuestionAndAnswer Then
' passwordQuestion = PasswordQuestionDDl.Text.Trim()
' passwordAnswer = PasswordAnswerTextbox.Text
'End If
Try
Dim newUser As MembershipUser = Membership.CreateUser(Username, Password, Email, Nothing, Nothing, False, status)
If newUser Is Nothing Then
Return GetErrorMessage(status)
Else
CreateUser_AugmentedUpdate(Username, JobTitleID, Prfx, fname, Mname, Lname, Initial, _
disname, UsrDOB, TelNum, UsrSignature, UsrImg_aURL, UsrImg_rURL)
Return "User has been Created Successfully" + JobTitleID
End If
Catch
Return "Create User Phase 1 Error. Please refer to your database developer"
End Try
End Function
Now behind this code, I put a trigger on the asp users table to insert the new userID in a different table. My SQL stored procedure (aspnet_Users_CreateUser_AugmentedUpdate) run a record update on the new table,
The code works beautifully but is it a good practice?
Thanks
Your implementation is correct, since we could not use Transaction in Membership Provider.
You will need to make sure user enters valid data before calling Membership.CreateUser. So I'll do some type of validations before that line. Otherwise, you will end up with dangling data.
Just a minor improvement which is not related to Membership. If you pass more than 3 arguments to a method, you might want to consider using object. You can read more at Clean Code by Robert C. Martin.
Public Function CreateUser_AugmentedUpdate(ByVal user As UserModel)
You can use ternary operator to shorten if statement.
SQLCmd.Parameters.Add("#TelNum", SqlDbType.NChar).Value =
If(String.IsNullOrEmpty(TelNum), DBNull.Value, TelNum.ToString)

Handle DBNull in an object initializer

In my asp.net web service, I have an object class which get data from database, but I counter the following problem when some data is null in database:
(1) If I don't handle the NULL value in database and use the code as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
.Address = dr("ADDRESS") _
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.
(2) if I handle the NULL in database as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
If dr("ADDRESS") = System.DBNull.Value Then
.Address = ""
Else
.Address = dr("ADDRESS") _
End if
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
Compiler Error Message: BC30985: Name of field or property being initialized in an object initializer must start with '.'.
I want to know how to handle the DBNull value for string and date in an object initializer.
You can use Convert.ToString
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim registerDate As Date
If Date.TryParse(Convert.ToString(dr("REGISTER_DATE")), registerDate ) = False Then
'Do what you need to do if the cell is not a valid date time value
End If
detail = New customerInfo() With { _
.CustomerID = Convert.ToString(dr("CUSTOMER_ID")), _
.CustomerName = Convert.ToString(dr("CUSTOMER_NAME")), _
.RegisterDate = registerDate.ToString("dd/MM/yyyy"), _
.Address = Convert.ToString(dr("ADDRESS"))
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Edited based on OP's comment below.
While the other methods would work, I think a re-usable extension method with generics support would be ideal.
You can pass the work off to the extension method and check if the value is equal to the value of DBNull.Value
Public Module DataRowExtensions
<System.Runtime.CompilerServices.Extension>
Public Function GetValueOrDefault(Of TExpectedType)(dr As DataRow, propertyName As String) As TExpectedType
If DBNull.Value.Equals(dr(propertyName)) Then
Return Nothing
End If
Return DirectCast(dr(propertyName), TExpectedType)
End Function
End Module
You can see this DotNetFiddle to see it in action with various data types.
Do make note that the extension method Field<T> does exist and is similar, but it doesn't handle DBNull values.
You can't use an if statement inside an object initializer like that.
You have to instantiate the object, then set the properties in separate lines.
detail = New customerInfo()
'Then in separate lines, populate the properties individually
If dr("ADDRESS") = System.DBNull.Value Then
detail.Address = ""
Else
detail.Address = dr("ADDRESS")

Insert array from query string into SQL 2005

I am trying to insert an array into SQL with no luck. I get the string from a GPRS device that looks like this:
/WeightBridge.aspx?ReadeID=A1B5A0F5C4E4A1B5A0F5C4E4&TagID=45B6C56A90B645B6C56A90B6,A47B1256A45F0843,B49B1256A45F08FF,30 SEP 2010 21:33:59,I,&Custom=Vehicle Num
All I want to do is to split the TagID array and insert it with the rest of the string into a SQL table. The TagID array must inserted into the following colomns in the DB. TagID, TID, UserMemory, DateTime and Direction. After the insert I just give a response that the insert was successfull or failed. Thank you
My code this far:
Imports System.Data.Sql
Imports System.Data.SqlClient
Partial Class WeightBridge
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
insertValue()
End Sub
Private Sub insertValue()
Dim sqlConn As New SqlConnection
Dim strConnection As String
Dim MyTagID As String
Dim MyReaderID As String
Dim MyCustom As String
Dim MyTagArray As Array
Dim i As Integer
'Request TagID Array
MyTagID = Request("TagID")
If MyTagID.Length > 0 Then
'Response.Write(MyTagID)
'Split TagID Array
MyTagArray = Split(MyTagID, ",")
For i = 0 To UBound(MyTagArray) - 1
Next
End If
Try
strConnection = "My Connection String"
sqlConn = New SqlConnection(strConnection)
Dim InsertCommand As New SqlCommand("INSERT INTO WeightBridge(ReaderID, TagID, TID, UserMemory, DateTime, Direction, Custom) VALUES ( '" & Request("ReaderID") & "', '0','0','0','0','0', '" & Request("Custom") & "')", sqlConn)
sqlConn.Open()
InsertCommand.ExecuteNonQuery()
sqlConn.Close()
Catch ex As Exception
Response.Write("FailedNo")
End Try
Response.Write("Success")
End Sub
End Class
There is a comma at the end of your TagID QueryString.
Besides, have a look at following code:
Dim allCols() As String = Request("TagID").Split(","c)
Dim tagID As String = allCols(0)
Dim tID As String = allCols(1)
Dim usermemory As String = allCols(2)
Dim dateTime As String = allCols(3)
Dim direction As String = allCols(4)
'........
You should read this article because you are widely open for sql-injection attacks.

Resources