async function in mvc4 vb.net - vb.net

i have the below structure :
this is my controller :
Public Function InsertRegistration() as string
dim res = t.Insertregistration(jsonparam.status)
return res
End Function
this is my class :
Public Function InsertRegistration(byval status as string) as string
sql.Insertregistration(status)
return "1"
End Function
this is my model function :
Public Function InsertRegistration(ByVal status As String) As Boolean
Dim TConnSQL As New SqlConnection(sql)
Dim CommSQL As New SqlClient.SqlCommand("JK_SP_INSERT_PROFILE", TConnSQL)
Dim paramSQL As SqlClient.SqlParameter
Dim data_ada As SqlDataAdapter
Dim dt As DataSet
Try
CommSQL.CommandType = CommandType.StoredProcedure
paramSQL = New SqlClient.SqlParameter("#STATUS", SqlDbType.NVarChar, 100)
paramSQL.Direction = ParameterDirection.Input
paramSQL.Value = STATUS
CommSQL.Parameters.Add(paramSQL)
CommSQL.ExecuteNonQuery()
InsertRegistration= True
Catch ex As System.Data.SqlClient.SqlException
WriteToText("Nbl.InsertRegistration", ex.ToString)
InsertRegistration= False
Catch ex As Exception
WriteToText("Nbl.InsertRegistration", ex.ToString)
InsertRegistration= False
Finally
If (IsNothing(CommSQL) = False) Then CommSQL.Dispose()
If TConnSQL.State <> ConnectionState.Closed Then TConnSQL.Close()
End Try
End Function
is there a way to return the result 1 in an asynchronous way that the function sql.Insertregistration(status) keeps running in background after i return the result to the client?

Simply put your function sql.Insertregistration(status) as in below code:
(new Task<bool>(() =>
{
return sql.Insertregistration(status);
})).Start();
Note: Please take care of the cross thread ooperations.

Related

getting data from mysql database by using thread in vb.,net

I'm trying to get data from database but I got an error:
There is already an open DataReader associated with this Connection
which must be closed first
what I did is the following codes:
1: I have a module that contains the following sub:
Public Function CheckServerConn() As Boolean
Try
_ServerConnStr = New MySqlConnection(My.Settings.DbPath)
If _ServerConnStr.State = ConnectionState.Open Then
_ServerConnStr.Close()
End If
If _ServerConnStr.State = ConnectionState.Closed Then
_ServerConnStr.Open()
Return True
End If
Catch ex As Exception
MsgBox("Check The Conn " & ex.Message, Me_MsgInfoStyle, Me_MsgCaptionStr)
Return False
End Try
#Disable Warning BC42353 ' Function doesn't return a value on all code paths
End Function
2: I have this subroutine in class called "ClsMySql":
'GetData
Public Sub GetData(ByVal SqlStr As String, ByVal xDt As DataTable, ByVal xPar() As MySqlParameter)
Using xCmd As New MySqlCommand() With {
.CommandType = CommandType.Text,
.CommandText = SqlStr,
.Connection = _ServerConnStr,
.CommandTimeout = 5000000
}
If xPar IsNot Nothing Then
For i As Integer = 0 To xPar.Length - 1
xCmd.Parameters.Add(xPar(i))
Next
End If
Using xDa As New MySqlDataAdapter(xCmd)
xDa.Fill(xDt)
End Using
xDt.Dispose()
End Using
End Sub
3: I have a class for the table that have the following method:
Public Sub MySql_Get_Daf()
xClsMySql = New ClsMySql
Dim SqlStr As String = "SELECT RegID,RegType, tblregs1.`RegRef`,`RegDate`, COUNT(`RegdID`) AS xCount
,IF(COUNT(`RegdID`) =3,'Ok','Error') AS xResult FROM tblregs1
INNER JOIN tblregs2 ON tblregs2.RegRef = tblregs1.RegRef
WHERE `RegType` = 'Daf'
GROUP BY tblregs1.`RegRef`
ORDER BY COUNT(`RegdID`) ASC"
Dt_Get_Daf = New DataTable()
xClsMySql.GetData(SqlStr, Dt_Get_Daf, Nothing)
End Sub
Public Sub MySql_Get_Qbd()
xClsMySql = New ClsMySql
Dim SqlStr As String = "SELECT RegID,RegType, tblregs1.`RegRef`,`RegDate`, COUNT(`RegdID`) AS xCount
,IF(COUNT(`RegdID`) =3,'Ok','Error') AS xResult FROM tblregs1
INNER JOIN tblregs2 ON tblregs2.RegRef = tblregs1.RegRef
WHERE `RegType` = 'Qbd'
GROUP BY tblregs1.`RegRef`
ORDER BY COUNT(`RegdID`) ASC"
Dt_Get_Qbd = New DataTable()
xClsMySql.GetData(SqlStr, Dt_Get_Qbd, Nothing)
End Sub
Public Sub MySql_Get_All()
Dim xThread As Thread = New Thread(Sub() MySql_Get_Daf())
Dim xThread2 As Thread = New Thread(Sub() MySql_Get_Qbd())
xThread.Start()
xThread2.Start()
End Sub
when I call MySql_Get_All by a button it gives me the next error:
There is already an open DataReader associated with this Connection
which must be closed first
can anybody tell me what's the wrong here

What is wrong with my code (VB. NET async wait and httplistener)

I am trying to run a httplistener in order to receive a call back from an web application
However the never goes past context = Await httpListener.GetContextAsync
I can telnet to the port of the listener and it responds.
Class SSO
Public Sub AuthorizeAsync()
Me.oAccessToken = Operations.AuthorizeAsync.Result
End Sub
'
Class Operations
Shared Async Function AuthorizeAsync() As Task(Of SSO.AccessToken)
Dim AccessToken As SSO.AccessToken
Dim AuthorizationCodeTask As Task(Of String)
Dim cts As New System.Threading.CancellationTokenSource
AuthorizationCodeTask = Operations.RunCallbackListenAsync(cts.Token)
Try
OpenAutorizationUrl()
Dim t As String
t = Await AuthorizationCodeTask
AccessToken = GetAccessToken(t)
Catch ex As Exception
logger.LogException(ex)
Throw ex
End Try
Return AccessToken
End Function
Private Shared Async Function RunCallbackListenAsync(ByVal cts As System.Threading.CancellationToken) As Task(Of String)
Dim retval As String = Nothing
Dim blGo As Boolean = True
Dim httpListener As New System.Net.HttpListener
httpListener.Prefixes.Add(My.Settings.APICallBack)
httpListener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous
httpListener.Start()
If httpListener.IsListening Then
Dim request As System.Net.HttpListenerRequest
Dim context As System.Net.HttpListenerContext
context = Await httpListener.GetContextAsync
While Not cts.IsCancellationRequested And blGo
context = Await httpListener.GetContextAsync
Try
If cts.IsCancellationRequested Then
context.Response.Abort()
End If
request = context.Request
Catch ex As Exception
logger.LogException(ex)
End Try
blGo = False
End While
If Not IsNothing(request) Then
retval = ProcessRequest(request)
Else
Throw New ApplicationException("RunCallbackListenAsync: The request is Nothing")
End If
httpListener.Close()
Else
Throw New ApplicationException("RunCallbackListenAsync: listener is not listening")
End If
Return retval
End Function
End class
what could by causing the blocking at context = Await httpListener.GetContextAsync?

Variable 'reader' is used before it has been assigned a value. A null reference exception could result at run time

Trying to fix a warning and not sure how to restructure code as reader.IsClosed is throwing a warning that states "Variable 'reader' is used before it has been assigned a value. A null reference exception could result at run time." Logistically, since reader As SqlDataReader && reader is not initialized with a value then I could ignore as should be fine at runtime, but my inexperience would make me believe there is a better way?
Public Function GetTotalItems(ByVal userId As Long) As Int16
Dim lstParam As List(Of SqlParameter) = New List(Of SqlParameter)()
Dim tablMd = Me.GetMetaData()
Dim retList As ArrayList = New ArrayList()
lstParam.Add(New SqlClient.SqlParameter("#" + tablMd.PrimaryKey.ColumnName, 0))
lstParam.Add(New SqlClient.SqlParameter("#UserID", userId))
lstParam.Add(New SqlClient.SqlParameter("#ActionFlag", "SELECT_ITEMS_COUNT"))
Dim spName As String = Me.GetStoreProcname()
Dim reader As SqlDataReader
Try
reader = SqlHelper.ExecuteReader(
Utility.GetConnectionStringSetting(),
CommandType.StoredProcedure,
Me.GetStoreProcname(),
lstParam.ToArray()
)
If (reader.HasRows = True) Then
If (reader.Read()) Then
Dim value As Object = reader(0)
Return CInt(value)
End If
End If
Catch ex As Exception
Throw
Finally
If Not reader.IsClosed Then
reader.Close()
End If
End Try
Return 0
End Function
We can narrow the problem down to this excerpt:
Dim reader As SqlDataReader
Try
reader = SqlHelper.ExecuteReader( ... )
Finally
If Not reader.IsClosed Then reader.Close()
End Try
The problem comes if an exception is thrown by the ExecuteReader() function. In that event, the reader variable is never assigned a value. It's still Nothing when you try to evaluate reader.IsClosed, and that will cause an exception.
Given you don't actually do anything with the exception and the SqlHelper takes care of the connection and command objects, you can narrow the entire function down to just this:
Public Function GetTotalItems(ByVal userId As Long) As Int16
Dim lstParam = {
New SqlClient.SqlParameter("#" + Me.GetMetaData().PrimaryKey.ColumnName, 0),
New SqlClient.SqlParameter("#UserID", userId),
New SqlClient.SqlParameter("#ActionFlag", "SELECT_ITEMS_COUNT")
}
Using reader As SqlDataReader = SqlHelper.ExecuteReader(
Utility.GetConnectionStringSetting(),
CommandType.StoredProcedure,
Me.GetStoreProcname(),
lstParam)
If reader.Read() Then Return CInt(reader(0))
End Using
Return 0
End Function
#jmcilhinney, #o_O, #Chris Dunaway ... Thank you for the help + appreciation + admiration for your knowledge + reverence == deverence(); ... This removed the error:
Public Function GetTotalAmount(ByVal userId As Long) As Decimal
Dim lstParam As List(Of SqlParameter) = New List(Of SqlParameter)()
Dim tablMd = Me.GetMetaData()
Dim retList As ArrayList = New ArrayList()
lstParam.Add(New SqlClient.SqlParameter("#" + tablMd.PrimaryKey.ColumnName, 0))
lstParam.Add(New SqlClient.SqlParameter("#UserID", userId))
lstParam.Add(New SqlClient.SqlParameter("#ActionFlag", "SELECT_TOTAL_AMOUNT"))
Dim spName As String = Me.GetStoreProcname()
Using reader As SqlDataReader = SqlHelper.ExecuteReader(
Utility.GetConnectionStringSetting(),
CommandType.StoredProcedure,
Me.GetStoreProcname(),
lstParam.ToArray()
)
If (reader.HasRows = True) Then
If (reader.Read()) Then
Dim value As Object = reader(0)
Return CDec(value)
End If
End If
End Using
Return 0
End Function

VB.Net freezing when adding 10000+ rows to SQL from list

I am running a RESTful API service which gets data from a server as a JSON string. Around 20000 rows are being selected.
Dim js As New JavaScriptSerializer()
Dim prodlist As List(Of Product) = js.Deserialize(Of List(Of Product))(JSONreturn)
The 20000 rows are populated in the list prodlist. Checked the count and manually verified the list.
I need to insert these rows in a client machine. However, while inserting the rows, it freezes or stops after inserting around 600-700 rows. Below is the code I am using for inserting.
For Each item As Product In prodlist
Dim SPName As String = "someSPname"
With connectionstring
.Clear()
.Parameters("#itemnumber", SqlDbType.VarChar, ParameterDirection.Input, , item.itemnumber
.Parameters("#itemtype", SqlDbType.VarChar, ParameterDirection.Input, , item.itemtype)
.Parameters("#DESCRIPTION", SqlDbType.VarChar, ParameterDirection.Input, , item.DESCRIPTION)
.Execute(SPName)
End With
Next
No error is thrown. It just freezes after inserting roughly 600-700 rows everytime.
Bulk insert is not an option. How do I resolve this?
UPDATE : Adding connection class. Pretty sure there is no issue with this :
Public Class ConnectionClass
Public ReadOnly Property ConnectionString() As String
Get
Return GetConfiguration()
End Get
End Property
Public Sub Parameters(ByVal param_name As String, ByVal type As SqlDbType, ByVal direction As ParameterDirection, Optional param_size As Int32 = Nothing, Optional param_value As Object = Nothing)
Dim sqlParam As SqlParameter = Nothing
Try
sqlParam = New SqlParameter(param_name, type)
sqlParam.Size = param_size
sqlParam.Direction = direction
sqlParam.Value = param_value
Lstparam.Add(sqlParam)
Finally
If sqlParam IsNot Nothing Then
sqlParam = Nothing
End If
End Try
End Sub
Public Sub Execute(ByVal strSpName As String, Optional ByVal Type As CommandType = CommandType.StoredProcedure)
Try
sqlcmd = New SqlCommand()
sqlcmd.Connection = connection
''Setting the timeout to 50 mins as setup in the previous application
sqlcmd.CommandTimeout = 3000
If transaction IsNot Nothing Then
sqlcmd.Transaction = transaction
End If
sqlcmd.CommandType = Type
sqlcmd.CommandText = strSpName
For Each argument As SqlParameter In Lstparam
sqlcmd.Parameters.Add(argument)
Next
For introw As Integer = 0 To sqlcmd.Parameters.Count - 1
If sqlcmd.Parameters.Item(introw).ParameterName.Contains("Parameter") Then
sqlcmd.Parameters.Item(introw).ParameterName = String.Empty
End If
Next
sqlcmd.ExecuteNonQuery()
Catch ex As Exception
Throw
End Try
End Sub
Public Sub Clear()
ClearParameters()
Lstparam.Clear()
End Sub
Public Sub ClearParameters()
If Not sqlcmd Is Nothing Then
Do Until sqlcmd.Parameters.Count = 0
sqlcmd.Parameters.Clear()
Loop
End If
End Sub
Public Function GetConfiguration() As String
Dim sbConnectionString As New StringBuilder
With sbConnectionString
.Append("Data Source=")
.Append(ServerName)
.Append(";")
.Append("Initial Catalog =")
.Append(DatabaseName)
.Append(";")
.Append("User ID =")
.Append(UserName)
.Append(";")
.Append("Password =")
.Append(UserPassword)
End With
Return sbConnectionString.ToString()
End Function
Public Function CreateClientConnection() As SqlConnection
Dim connectionString As String
Try
connectionString = GetConfiguration()
Dim substrings() As String = connectionString.ToUpper.Split(";")
Dim substrings1() As String = connection.ConnectionString.ToUpper.Split(";")
If Not (connection.State = ConnectionState.Open) Then
connection.ConnectionString = connectionString
connection.Open()
ElseIf Not (Trim(substrings(0)) = Trim(substrings1(0))) Then
If connection IsNot Nothing Then
connection.Dispose()
End If
connection.ConnectionString = connectionString
connection.Open()
End If
Return connection
Catch ex As Exception
If connection IsNot Nothing Then
connection.Dispose()
End If
Throw ex
End Try
End Function
End Class

message id from GetResultData

I cannot seem to get or store the id of the post message I create. I am using this code to post a message:
Try
Dim fb = New FacebookClient(_accessToken)
AddHandler fb.PostCompleted, Function(o, e)
If (e.Cancelled) Then
ElseIf e.Error IsNot Nothing Then
MessageBox.Show(e.Error.Message)
Else
Dim result As Object = e.GetResultData()
_lastMessageId = result.Id
End If
Return MessageBox.Show("Message Posted successfully")
End Function
Dim parameters As Object = New ExpandoObject()
parameters.message = TextBox1.Text
fb.PostTaskAsync("me/feed", parameters)
MsgBox("This is the last message id " & _lastMessageId)
Catch ex As FacebookApiException
MessageBox.Show(ex.Message)
End Try
I just want to store the posted id so I can delete it later.
Here is the working code that i came up with thanks to prabir
Dim fb = New FacebookClient(_accessToken)
Dim parameters As Object = New ExpandoObject()
parameters.message = "Testing"
Dim task = fb.PostTaskAsync("me/feed", parameters)
task.ContinueWith(Function(t)
If t.Exception Is Nothing Then
Dim result As Object = t.Result
_lastMessageId = result.id
Else
MsgBox("error occurred")
End If
Return t.Result
End Function)
here is c# code which might help you get started with it.
Since you are using XTaskAsync methods use ContinueWith instead of PostCompleted.
fb.PostTaskAsync("me/feed", parameters)
.ContinueWith(t= > {
if(!t.IsFaulted) {
dynamic result = t.Result;
}
});
XTaskAsync methods returns Task<object>