The commit transaction request has no corresponding begin transaction using ADO.net - ado.net

I want to update the records batch wise in SqlTransaction. In every batch i am updating 50 records. If any one record fails to update i want rollback those 50 records. I have written this code in while loop. But i am getting following error randomly.
'The commit transaction request has no corresponding begin transaction'.
Following is my code:
Dim _completed as Integer=0
Dim sqlCon As SqlClient.SqlConnection = Nothing
Dim sqlTransaction As SqlClient.SqlTransaction = Nothing
Dim lstq as List(of SqlCommand) 'It contains list of update queries
sqlCon = New SqlClient.SqlConnection(AIMSCommon.sqlServerConnection)
sqlCon.Open()
While True
Dim _res = lstq.Skip(_completed).Take(40)
If _res.Count = 0 Then Exit While
If sqlCon.State <> ConnectionState.Open Then
sqlCon = New SqlClient.SqlConnection(AIMSCommon.sqlServerConnection)
sqlCon.Open()
End If
Try
sqlTransaction = sqlCon.BeginTransaction()
For Each cls In _res
Try
cls.Connection = sqlCon
cls.Transaction = sqlTransaction
Dim i As Integer = cls.ExecuteNonQuery()
cls.Dispose()
Catch ex As Exception
If cls IsNot Nothing Then
cls.Dispose()
End If
Throw ex
End Try
Next
sqlTransaction.Commit()
sqlTransaction.Dispose()
sqlTransaction = Nothing
_completed += _res.Count
Catch ex As Exception
sqlCon.Close()
sqlCon.Dispose()
If sqlTransaction IsNot Nothing Then
sqlTransaction.Rollback()
sqlTransaction.Dispose()
End If
If sqlCon IsNot Nothing Then
sqlCon.Close()
sqlCon.Dispose()
End If
End Try
End While
If sqlCon IsNot Nothing Then
sqlCon.Close()
sqlCon.Dispose()
End If

Related

Getting Email Addresses for Recipients (Outlook)

I have a code that I was able to string together that logs my sent emails into an excel sheet so i can use that data for other analysis.
In it, I have it resolving the name into an email as outlook shortens it ("Jimenez, Ramon" = email#address.com) as outlook configured this and it works when i send an email to anyone in my company as they are in my address book.
Now, when I email anyone outside it defaults to lastName, firstName so it is not converting this and logging it.
I thought the code I have in here already does this, but I guess not. I have already come this far and I am NOT a software guru at all. Does anyone have insight on how I can also include this as well?? Please see code below:
Private WithEvents Items As Outlook.Items
Const strFile As String = "C:\Users\a0227084\Videos\work\test.xlsx"
Private Sub Application_Startup()
Dim OLApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set OLApp = Outlook.Application
Set objNS = OLApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
FullName = Split(Msg.To, ";")
For i = 0 To UBound(FullName)
If i = 0 Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
ElseIf ResolveDisplayNameToSMTP(FullName(i)) <> "" Then
STRNAME = ResolveDisplayNameToSMTP(FullName(i))
Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
Next i
'Call Write_to_excel(CStr(Msg.ReceivedTime), CStr(Msg.Subject), CStr(STRNAME))
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
Sub tes2t()
End Sub
Function getRecepientEmailAddress(eml As Variant)
Set out = CreateObject("System.Collections.Arraylist") ' a JavaScript-y array
For Each emlAddr In eml.Recipients
If Left(emlAddr.Address, 1) = "/" Then
' it's an Exchange email address... resolve it to an SMTP email address
out.Add ResolveDisplayNameToSMTP(emlAddr)
Else
out.Add emlAddr.Address
End If
Next
getRecepientEmailAddres = Join(out.ToArray(), ";")
End Function
Function ResolveDisplayNameToSMTP(sFromName) As String
' takes a Display Name (i.e. "James Smith") and turns it into an email address (james.smith#myco.com)
' necessary because the Outlook address is a long, convoluted string when the email is going to someone in the organization.
' source: https://stackoverflow.com/questions/31161726/creating-a-check-names-button-in-excel
Dim OLApp As Object 'Outlook.Application
Dim oRecip As Object 'Outlook.Recipient
Dim oEU As Object 'Outlook.ExchangeUser
Dim oEDL As Object 'Outlook.ExchangeDistributionList
Set OLApp = CreateObject("Outlook.Application")
Set oRecip = OLApp.Session.CreateRecipient(sFromName)
oRecip.Resolve
If oRecip.Resolved Then
Select Case oRecip.AddressEntry.AddressEntryUserType
Case 0, 5 'olExchangeUserAddressEntry & olExchangeRemoteUserAddressEntry
Set oEU = oRecip.AddressEntry.GetExchangeUser
If Not (oEU Is Nothing) Then
ResolveDisplayNameToSMTP = oEU.PrimarySmtpAddress
End If
Case 10, 30 'olOutlookContactAddressEntry & 'olSmtpAddressEntry
Dim PR_SMTP_ADDRESS As String
PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
End Select
End If
End Function
Sub Write_to_excel(str1 As String, str2 As String, str3 As String)
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceWH As Worksheet
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
Set sourceWB = Workbooks.Open(strFile, False, False)
Set sourceWH = sourceWB.Worksheets("Sheet1")
sourceWB.Activate
With sourceWH
lastrow = .Cells(.rows.Count, "A").End(xlUp).Row
End With
sourceWH.Cells(lastrow + 1, 1) = str1
sourceWH.Cells(lastrow + 1, 2) = str2
sourceWH.Cells(lastrow + 1, 3) = str3
sourceWB.Save
sourceWB.Close
End Sub
Error message and corrected code
Regards,
Ramon
First of all, there is no need to create a new Application instance in the ResolveDisplayNameToSMTP method:
Set OLApp = CreateObject("Outlook.Application")
Instead, you can use the Application property available in the Outlook VBA editor out of the box.
Second, you need to use the following code to get the SMTP address from the AddressEntry object:
Dim PR_SMTP_ADDRESS As String
Set PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
ResolveDisplayNameToSMTP = oRecip.AddressEntry.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
Instead of the following line:
ResolveDisplayNameToSMTP = oRecip.AddressEntry.Address
Read more about that in the How to get the SMTP Address of the Sender of a Mail Item using Outlook Object Model? article.

Updated Yahoo Weather API - .NET

I'm trying to implement the newest yahoo weather API in a .NET application (the one we were using was discontinued in favor of this new one): https://developer.yahoo.com/weather/documentation.html#commercial
Their only examples are in PHP and Java. I've done my best to convert the Java example to .NET but I still am getting a "401 - Unauthorized" response. I've gone over my code several times and cannot find any problems so I'm hoping someone else will be able to see where I went wrong. Code is below.
Private Sub _WeatherLoader_DoWork(sender As Object, e As DoWorkEventArgs)
Try
Dim oauth As New OAuth.OAuthBase
Dim forecastRssResponse As query
Dim appId As String = My.Settings.YahooAppID
Dim consumerKey As String = My.Settings.YahooAPIConsumerKey
Dim yahooUri As String = String.Format("{0}?location=billings,mt&format=xml", YAHOO_WEATHER_API_BASE_ENDPOINT)
Dim oAuthTimestamp As Integer = oauth.GenerateTimeStamp()
Dim oAuthNonce As String = oauth.GenerateNonce()
Dim parameters As New List(Of String)
Try
parameters.Add(String.Format("oauth_consumer_key={0}", consumerKey))
parameters.Add(String.Format("oauth_nonce={0}", oAuthNonce))
parameters.Add("oauth_signature_method=HMAC-SHA1")
parameters.Add(String.Format("oauth_timestamp={0}", oAuthTimestamp.ToString()))
parameters.Add("oauth_version=1.0")
' Encode the location
parameters.Add(String.Format("location={0}", HttpUtility.UrlEncode("billings,mt", Encoding.UTF8)))
parameters.Add("format=xml")
' Sort parameters ascending
parameters = parameters.OrderBy(Function(item) item).ToList()
Dim i As Integer = 0
Dim builder As New StringBuilder()
Do While (i < parameters.Count())
builder.Append(String.Format("{0}{1}", If(i > 0, "&", String.Empty), parameters(i)))
i += 1
Loop
Dim signatureString As String = String.Format("GET&{0}&{1}", HttpUtility.UrlEncode(YAHOO_WEATHER_API_BASE_ENDPOINT, Encoding.UTF8), HttpUtility.UrlEncode(builder.ToString(), Encoding.UTF8))
Dim oAuthSignature As String = _CreateOauthSignature(signatureString)
Dim authorizationLine As String = String.Format("OAuth oauth_consumer_key={0}, oauth_nonce={1}, oauth_timestamp={2}, oauth_signature_method=HMAC-SHA1, oauth_signature={3}, oauth_version=1.0", consumerKey, oAuthNonce, oAuthTimestamp, oAuthSignature)
Dim forecastRequest As WebRequest = WebRequest.Create(yahooUri)
forecastRequest.Headers.Add("Authorization", authorizationLine)
forecastRequest.Headers.Add("Yahoo-App-Id", appId)
' Cast to HttpWebRequest to set ContentType through property
CType(forecastRequest, HttpWebRequest).ContentType = "text/xml"
Dim forecastResponse As WebResponse = forecastRequest.GetResponse()
If forecastResponse IsNot Nothing Then
Using responseStream As Stream = forecastResponse.GetResponseStream()
Dim rssDoc As New XmlDocument()
rssDoc.Load(responseStream)
forecastRssResponse = rssDoc.OuterXml().FromXml(Of query)()
End Using
e.Result = forecastRssResponse
End If
Catch ex As Exception
e.Result = Nothing
LoadingManually = False
End Try
Catch ex As Exception
modMain.SendDevErrorEmail(ex, "_WeatherLoader_DoWork in WeatherWidget", "Catch around dowork code in fired from refresh timer event in wether widget")
e.Result = Nothing
LoadingManually = False
End Try
End Sub
Private Function _CreateOauthSignature(baseInfo As String) As String
Dim secretKey As String = String.Format("{0}&", My.Settings.YahooAPIConsumerSecretKey)
Dim encoding As New System.Text.ASCIIEncoding()
Dim keyBytes As Byte() = encoding.GetBytes(secretKey)
Dim messageBytes As Byte() = encoding.GetBytes(baseInfo)
Dim hashMessage As Byte()
Using hmac As New HMACSHA1(keyBytes)
hashMessage = hmac.ComputeHash(messageBytes)
End Using
Return Convert.ToBase64String(hashMessage)
End Function
After painstakingly creating a Java app, pasting in the Java example and stepping through it I found that the issue is in a poorly implemented URL Decode function on the receiving end.
In the Java app, URL Encode uses upper case characters while in .NET HTTPUtility.URLEncode uses lower case characters. This is enough to throw off your signature and cause a 401 - Unauthorized error.
My solution was to create a string extension method that will URL Encode in upper case:
<Extension>
Public Function UppercaseURLEncode(ByVal sourceString As String) As String
Dim temp As Char() = HttpUtility.UrlEncode(sourceString).ToCharArray()
For i As Integer = 0 To temp.Length - 2
If temp(i).ToString().Equals("%", StringComparison.OrdinalIgnoreCase) Then
temp(i + 1) = Char.ToUpper(temp(i + 1))
temp(i + 2) = Char.ToUpper(temp(i + 2))
End If
Next
Return New String(temp)
End Function
Using this extension method my signature gets created exactly like the one in the Java app and I am able to retrieve the response.
Hope this helps other .net programmers with this issue!

how to hide other column

In my datagridview, I just want to show other fields such as ID,LastName,FirstName, and MiddleName and i dont want to show any fields but i want it to retrieve even it's hidden. But when i specify what i just want to show in my datagridview it causes runtime error.
this is my code to load the datagridview.
MysqlConn.Open()
Dim Query As String
Query = "select ID,LastName,FirstName,MiddleName from god.precord"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
SDA.Update(dbDataSet)
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
then this is my code for retrieve data into textboxes
Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
txtid.Text = row.Cells("ID").Value.ToString
txtlastname.Text = row.Cells("LastName").Value.ToString
txtfirstname.Text = row.Cells("FirstName").Value.ToString
txtmiddlename.Text = row.Cells("MiddleName").Value.ToString
txtaddress.Text = row.Cells("Address").Value.ToString
txtcontactno.Text = row.Cells("ContactNo").Value.ToString
txtgender.Text = row.Cells("Gender").Value.ToString
dtpbirthdate.Text = row.Cells("Birthdate").Value.ToString
txtage.Text = row.Cells("Age").Value.ToString
End If
End Sub
runtime error
please help me this is for my thesis
thankyou in advance <3
You have to add hidden column into the select query to retreive the data.
Hide the column from the DataGridView instead.
try
MysqlConn.Open()
Dim Query As String
Query = "select ID,LastName,FirstName,MiddleName,Address from god.precord"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
SDA.Update(dbDataSet)
DataGridView1.Columns("Address").Visible = false
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try

Backend sent unrecognized response type: u Error with Postgres 9.3 and npgsql

I upgraded my server yesterday from Postgres 9.1 to 9.3 and since then I've been getting an error: Backend sent unrecognized response type: u
I'm using npgsql to connect from my application to the server.
I remember that I used to get this error a while back and I haven't seen it in a while.
A full line from my log is:
Backend sent unrecognized response type: u
INSERT INTO stockcodes_rating (item_code,rating,price_range,user_id,timestamp_of_rating) VALUES ('10245684','5','Reasonable','10832',now())
My code for the procedure is:
Public Function InsertRating(ByVal Stockcode As String, ByVal Rating As Integer, ByVal PriceRange As String, ByVal UserId As String) As String
Dim objDBWrite As dlNpgSQL
objDBWrite = New dlNpgSQL("PostgreConnectionStringWrite", ConfigurationManager.AppSettings("CurrentDatabase"))
tmpSQL = "INSERT INTO stockcodes_rating (item_code,rating,price_range,user_id,timestamp_of_rating) VALUES " & _
"('" & Stockcode.ToUpper & "','" & Rating & "','" & PriceRange & "','" & UserId & "',now())"
Try
objDBWrite.ExecuteQuery(tmpSQL)
Catch ex As Exception
objDBWrite.CloseConnection()
Return ex.Message
Finally
objDBWrite.CloseConnection()
End Try
Return "Success"
End Function
My code for the dlNpgSQLclass is:
Imports Npgsql
Public Class dlNpgSQL
Dim _sqlConnection As NpgsqlConnection
Dim _sqlCommand As NpgsqlCommand
Dim _sqlDataAdapter As NpgsqlDataAdapter
Dim _dataset As DataSet
Public Sub New()
On Error GoTo ErrZ
_sqlConnection = New NpgsqlConnection(ConfigurationManager.ConnectionStrings("PostgreRemoteConnectionString").ConnectionString)
Exit Sub
End Sub
Public Sub New(ByVal WhichConnectionString As String)
On Error GoTo ErrZ
_sqlConnection = New NpgsqlConnection(ConfigurationManager.ConnectionStrings(WhichConnectionString).ConnectionString)
Exit Sub
End Sub
Public Sub New(ByVal WhichConnectionString As String, ByVal WhichDB As String)
On Error GoTo ErrZ
_sqlConnection = New NpgsqlConnection(ConfigurationManager.ConnectionStrings(WhichConnectionString).ConnectionString & "database=" & WhichDB & ";")
Exit Sub
End Sub
Public Function OpenConnection() As NpgsqlConnection
Try
If _sqlConnection.State = ConnectionState.Closed Then
_sqlConnection.Open()
End If
Catch ex As Exception
End Try
Return _sqlConnection
End Function
Public Sub CloseConnection()
Try
If _sqlConnection.State = ConnectionState.Open Then
_sqlConnection.Close()
End If
Catch ex As Exception
End Try
End Sub
Public Function GetDataSet(ByVal strQuery As String) As DataSet
'NpgsqlEventLog.Level = LogLevel.Normal
'NpgsqlEventLog.LogName = ("c:\npgsql.log")
'NpgsqlEventLog.EchoMessages = True
_dataset = New DataSet
Try
_sqlDataAdapter = New NpgsqlDataAdapter(strQuery, OpenConnection)
_sqlDataAdapter.Fill(_dataset)
Catch ex As Exception
End Try
Return _dataset
End Function
Public Function ReleaseDataSet(ByRef ds As DataSet) As Boolean
Try
ds.Clear()
ds.Dispose()
Catch ex As Exception
End Try
Return True
End Function
Public Function ExecuteQuery(ByVal strQuery As String) As String
'NpgsqlEventLog.Level = LogLevel.Normal
'NpgsqlEventLog.LogName = ("c:\npgsql.log")
'NpgsqlEventLog.EchoMessages = True
Dim RecordsReturned As String = ""
Try
_sqlCommand = New NpgsqlCommand(strQuery, OpenConnection)
RecordsReturned = _sqlCommand.ExecuteNonQuery()
Catch ex As Exception
Return ""
End Try
Return RecordsReturned
End Function
Public Function isR(ByVal tmpDs As DataSet, Optional ByVal tablename As Integer = 0) As Boolean
Try
If tmpDs.Tables.Count > 0 Then
If tmpDs.Tables(0).Rows.Count > 0 Then
isR = True
Else
isR = False
End If
End If
Catch ex As Exception
isR = False
End Try
End Function
End Class
What version of npgsql are you using? You probably need to upgrade to 2.0.14.3.
Better yet, try out the 2.1.0-beta1 which is quite stable and about to be released.
The same thing happened to me using Npgsql 2.0.12.0 sharing the connection between threads. Making a new connection in each thread was the solution!

SSIS Script transformation error using ADO.NET

I'm getting an error that states Incorrect syntax near ')'. when executing my SSIS package. The error is being thrown by a Script transformation component in the DFT. From what I can tell it is being thrown by the sqlReader = sqlCmd.ExecuteReader() line. I have been looking at it for days now and can't seem to figure out what is causing the error. I've included the contents of the script component below. Anyone have any ideas?
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Imports System.Data.SqlClient
Public Class ScriptMain
Inherits UserComponent
Dim connMgr As IDTSConnectionManager90
Dim sqlConn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlParam As SqlParameter
Public Overrides Sub AcquireConnections(ByVal Transaction As Object)
connMgr = Me.Connections.connTalisma
sqlConn = CType(connMgr.AcquireConnection(Nothing), SqlConnection)
End Sub
Public Overrides Sub PreExecute()
sqlCmd = New SqlCommand("SELECT Name FROM dbo.Category WHERE CatID = #catid)", sqlConn)
sqlParam = New SqlParameter("#catid", SqlDbType.Int)
sqlCmd.Parameters.Add(sqlParam)
End Sub
Public Overrides Sub ReleaseConnections()
connMgr.ReleaseConnection(sqlConn)
End Sub
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Dim sqlReader As SqlDataReader
Dim delimitedField As String = Row.FinalCallReason
Dim delimiter As String = ";"
Dim tempField As String
If Not (String.IsNullOrEmpty(delimitedField)) Then
Dim DelimitedListArray() As String = delimitedField.Split(New String() {delimiter}, StringSplitOptions.RemoveEmptyEntries)
For Each item As String In DelimitedListArray
sqlCmd.Parameters("#catid").Value = CInt(item)
MsgBox(item)
Try
sqlReader = sqlCmd.ExecuteReader()
tempField = tempField + ";" + sqlReader.GetString(0)
Catch e As Exception
MsgBox("Error: " + e.Message)
End Try
Next
End If
Row.FinalCallReason = tempField
End Sub
End Class
In the following section of the code, change #catid) to #catid in the SqlCommand object initialization statement.
Remove the parentheses. It is not needed. The parentheses is causing the query to fail and hence the error message Incorrect syntax near ')'.
Public Overrides Sub PreExecute()
sqlCmd = New SqlCommand("SELECT Name FROM dbo.Category WHERE CatID = #catid)", sqlConn)
sqlParam = New SqlParameter("#catid", SqlDbType.Int)
sqlCmd.Parameters.Add(sqlParam)
End Sub