Sendgrid VB.net integration - sendgrid

I have copied the example from this post here at
Visual Basic (VB.NET) example code to send SendGrid email by a VB.NET windows app
to get this working in my vb website. I was able to get this to debug by changing the Module to a Class. It would not work as a module for me. I have uploaded it and placed my key into the web.config file. When I click the button at my live site, I don't receive an email. Also, when I check at Sendgrid.com for email stats, everything is zeroed out with no record of receiving any emails to forward. Here is my code:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Configuration
Imports SendGrid
Imports SendGrid.Helpers.Mail
Class sendgrid1
Sub Main(ByVal test As String)
TestSendGrid(test).Wait()
End Sub
Private Async Function TestSendGrid(ByVal test As String) As Task
Try
Dim apiKey = ConfigurationManager.AppSettings("ApiKey")
Dim client = New SendGridClient(apiKey)
Dim msg = New Helpers.Mail.SendGridMessage() With {
.From = New EmailAddress("admin#pacificwestcapital.net", test),
.Subject = "Hello World from the SendGrid VB.NET SDK!",
.PlainTextContent = "Hello, Email!",
.HtmlContent = "<strong>Hello, Email!</strong>"
}
msg.AddTo(New EmailAddress("pacwestcapital#aol.com", "Scot King"))
Dim response = Await client.SendEmailAsync(msg)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Function
End Class
Partial Class admin_sendgrid
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sg As New sendgrid1
Call sg.Main("Scot King")
End Sub
End Class
Can someone possibly explain why it isn't working?

Related

Hundreds of Running / Terminated threads a minute

I'm using PostgreSQL 9.5 and Npgsql 2.2.5.0 to connect from an ASP.NET web service written with VB.NET to the PostgreSQL server.
The webservice gets around 15 requests a second.
The connection string I use is:
<connectionStrings>
<add name="PostgreConnectionStringPCMRead"
connectionString="Server=xxx.xxx.xxx.xxx;Port=5432;User
Id=the_user;Password=the_password;Database=example;
CommandTimeout=600;Timeout=30;ConnectionLifeTime=30;
Pooling=False;"/>
</connectionStrings>
When I take a look at the Windows Resource Monitor, I see hundreds of Terminated connections.
I realise that I am using Pooling=False, however when I set Pooling=True, I get errors "Timeout while getting a connection from pool."
With every query I use the following Class (I've left in only the essential code):
Public Class dlNpgSQL
Dim _sqlCommand As NpgsqlCommand
Dim _sqlDataAdapter As NpgsqlDataAdapter
Dim _dataset As DataSet
Public Sub New()
_sqlConnection = New NpgsqlConnection(ConfigurationManager.
ConnectionStrings("connstring").ConnectionString)
End Sub
Public Function GetDataSet(ByVal strQuery As String) As DataSet
_dataset = New DataSet
_sqlDataAdapter = New NpgsqlDataAdapter(strQuery, OpenConnection)
_sqlDataAdapter.Fill(_dataset)
Return _dataset
End Function
Public Function OpenConnection() As NpgsqlConnection
If _sqlConnection.State = ConnectionState.Closed Then
_sqlConnection.Open()
End If
End Function
Public Sub CloseConnection()
If _sqlConnection.State = ConnectionState.Open Then
_sqlConnection.Close()
End If
End Function
End Class
And then the actual query:
Dim ds As DataSet
Dim objDBRead As New dlNpgSQL("connstring")
tmpSQL = "SELECT * FROM table1"
ds = objDBRead.GetDataSet(tmpSQL)
If (objDBRead IsNot Nothing) Then
objDBRead.CloseConnection()
End If
So obviously, I'm opening and closing the connection with each query.
Is this the correct way to do things?
Should I be using pooling, and if yes, why am I getting the errors and how can I fix the issue?
Thanks!

Returning editable ADO Recordsets to an MS Access Form using a Class Module

PREFACE: I am using SQL Server 2008 R2 BackEnd and MS Access 2007 for the FrontEnd
I have a Class Module that returns any ADO Recordset I want from the SQL Server. I can then assign this to any form RecordSource property.
The problem is that when I try to edit the fields it says "This form is read-only" in the status bar. I want the form to be editable.
I have two forms
FormEntities
FormEntitiesEdit
The FormEntitiesEdit form does NOT use the Class Module. Rather all the code is in the form itself.
The purpose of the class module is avoid redundancy and just be able to use the Class Module to get a recordset from SQL Server easily.
FIRST HERE IS MY GLOBAL MODULE
'Default error message. 'eh' stands for error handler
Public eh As String
'Global variables for universal use
Public conn As ADODB.Connection
Public rs As ADODB.Recordset
Public com As ADODB.Command
SECOND IS THE CLASS MODULE (Name is cADO).
THIS CLASS MODULE USES THE conn CONNECTION OBJECT ABOVE
Option Explicit
Private Const CONST_LockType = 3
Private Const CONST_CursorType = 1
Private Const CONST_CursorLocationServer = 3
Private Const CONST_CursorLocationClient = 2
Private m_Recordset As ADODB.Recordset
'For Public Recordset function
Private cSQL$
'**********************************************************************
Public Function cGetRecordset(ByRef sql) As ADODB.Recordset
Set m_Recordset = New ADODB.Recordset
cSQL = sql
cOpenRecordset
Set cGetRecordset = m_Recordset
End Function
'**********************************************************************
Public Property Set Recordset(Value As ADODB.Recordset)
'Assigns private variable a property
If Not Value Is Nothing Then Set m_Recordset = Value
End Property
'**********************************************************************
Public Property Get Recordset() As ADODB.Recordset
'Reads the recordset from the private variable and assigns to new object variable
Set Recordset = m_Recordset
End Property
'********************************** PRIVATE SECTION **********************************
Private Sub cOpenRecordset()
On Error GoTo eh
'Ensures that if a recordset is opened from previously that it closes before opening a new one
If m_Recordset.State adStateClosed Then m_Recordset.Close
Set m_Recordset.ActiveConnection = conn
With m_Recordset
.LockType = CONST_LockType
.CursorType = CONST_CursorType
.CursorLocation = CONST_CursorLocationClient
.Source = cSQL
.Open .Source
End With
If Not m_Recordset.EOF Then m_Recordset.MoveFirst
Exit Sub
eh:
eh = "Error # " & Str(Err.Number) & " was generated by " & _
Err.Source & Chr(13) & Err.Description
MsgBox eh, vbCritical, "Open Recordset System"
End Sub
'**********************************************************************
Private Sub cCloseRecordset()
m_Recordset.Close
Set m_Recordset = Nothing
End Sub
'**********************************************************************
Private Sub Class_Terminate()
If Not (m_Recordset Is Nothing) Then Set m_Recordset = Nothing
End Sub
THIRD IS THE CODE BEHIND MY FormEntities FORM (USES THE THE cADO CLASS MODULE)
Option Explicit
Dim db As cADO
'**********************************************************************
Private Sub Form_Current()
LoadTab
End Sub
'**********************************************************************
Private Sub Form_Load()
Set db = New cADO
FetchRecordSource
End Sub
'**********************************************************************
Private Sub FetchRecordSource()
db.cGetRecordset ("SELECT * FROM dbo.Entities")
Set Forms("fEntities").Recordset = db.Recordset
End Sub
FOURTH AND FINALLY IS THE CODE BEHIND THE FormEntitiesEdit FORM (THIS FORM DOES NOT USE THE CLASS MODULE AND I CAN EDIT IT)
Option Compare Database
Option Explicit
Dim rsEntity As New ADODB.Recordset
'**********************************************************************
Private Sub Form_Load()
FetchRecordSource
End Sub
'**********************************************************************
Private Sub FetchRecordSource()
Set rsEntity.ActiveConnection = conn
'Sets the record source for the main form
With rsEntity
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Source = "SELECT * FROM dbo.Entities"
.Open .Source
End With
Set Forms("fEntitiesEdit").Recordset = rsEntity
End Sub
'**********************************************************************
Private Sub CloseConn()
rsEntity.Close
End Sub
If Access Jet SQL could do the SQL I would bind this form to a Linked Table instead. However I am using a hierarchical (recursive) query which Jet SQL cannot do so I have to bypass the idea of bound forms to Linked Tables.
I have .Allow Edits and .AllowAdditions on the form set to true.
I also tried changing the .LockType on the ADO Recordset to
adOpenKeyset and
adOpenDynamic
My LockType is adLockOptimistic
As you can see the properties are set correctly to be able to edit the recordset I return.
I know this is true because when I use the FormEntitiesEdit form with the same properties it lets me edit the field. But when I use the Class Module to return (using the same properties) it says it's read-only.
This is important because as you can see it is a lot simpler to use the Class Module, just need it to return an editable recordset.
Anyone have ideas? suggestions?
The problem is here in the class' cOpenRecordset() method:
.CursorLocation = CONST_CursorLocationClient
Here is where you assign constant values ...
Private Const CONST_CursorLocationServer = 3
Private Const CONST_CursorLocationClient = 2
Unfortunately, you swapped those two values. Here are the ADODB.CursorLocationEnum constants ...
adUseClient = 3
adUseServer = 2
So your class is effectively doing this ...
.CursorLocation = adUseServer
But you need a client-side cursor if you want the recordset to be editable. I think your class approach may work if you simply redefine the constant, or you will expose a different problem ...
Private Const CONST_CursorLocationClient = 3
FormEntitiesEdit is editable because you're using the correct constant there ...
.CursorLocation = adUseClient

Creating a Class to Handle Access Form Control Events

I'm trying to create a Class which will handle multiple Control Events in Access. This is to save the repetition of typing out many lines of identical code.
I've followed the answer located on the following page, but with a few adjustments to tailor it to Access rahter than Excel.
How to assign a common procedure for multiple buttons?
My Class code below:
Option Compare Database
Public WithEvents ct As Access.CommandButton 'Changed object type to something recognised by Access
Public Sub ct_Click()
MsgBox ct.Name & " clicked!"
End Sub
My Form code below:
Option Compare Database
Private listenerCollection As New Collection
Private Sub Form_Load()
Dim ctItem
Dim listener As clListener
For Each ctItem In Me.Controls
If ctItem.ControlType = acCommandButton Then 'Changed to test whether control is a Command Button
Set listener = New clListener
Set listener.ct = ctItem
listenerCollection.Add listener
End If
Next
End Sub
I have noted with comments where I have made changes to the (working) Excel code. I think the problem comes with the object declaration in the Class. Note: no errors are thrown during this procedure; it simply doesn't trigger the event.
Thanks in advance!
Edit:
I've since narrowed the problem down to there being no '[Event Procedure]' in the 'On Click' Event. If I add it manually, the Class works as expected. Obviously, I don't want to have to add these manually - it defeats the object. Any ideas how I would go about this?
In your OnLoad event you can add this line
Dim ctItem
Dim listener As clListener
For Each ctItem In Me.Controls
If ctItem.ControlType = acCommandButton Then 'Changed to test whether control is a Command Button
Set listener = New clListener
Set listener.ct = ctItem
listener.ct.OnClick = "[Event Procedure]" '<------- Assigned the event handler
listenerCollection.Add listener
End If
Next
Although I'm not sure if this is more is less code than just double clicking in the OnClick in the designer and pasting in a method call. It's cool regardless.
Edit:
You could change your class like this
Public WithEvents ct As Access.CommandButton 'Changed object type to something recognised by Access
Public Function AddControl(ctrl as Access.CommandButton) as Access.CommandButton
set ct = ctrl
ct.OnClick = "[Event Procedure]"
Set AddControl = ct
End Function
Public Sub ct_Click()
MsgBox ct.Name & " clicked!"
End Sub
Then in your form you can add a ct like this
For Each ctItem In Me.Controls
If ctItem.ControlType = acCommandButton Then 'Changed to test whether control is a Command Button
Set listener = New clListener
listener.AddControl ctItem
listenerCollection.Add listener
End If
Next
Now the event handler is added in the class.
A Generic Approach to handling Access Form Controls input with a class module:
This code was crafted to handle an application written within a popup window. The Main Form contains a tab control where each tab contains its own subform to either a linked child table or an independent table. The use or non-use of a tab control shouldn't make any difference to the class module processing.
The code can be trimmed to meet your application's needs. For example one could remove controls that one is not using from the class module. Likewise, the controls collection subroutine can be selective by using the TypeName(Ctl) statement to filter the controls that get added to the collection.
In a class module called clsMultipleControls put the following code.
Option Compare Database
Option Explicit
Private m_PassedControl As Control
Private WithEvents atch As Attachment
Private WithEvents bfrm As BoundObjectFrame
Private WithEvents chk As CheckBox
Private WithEvents cbo As ComboBox
Private WithEvents btn As CommandButton
Private WithEvents cctl As CustomControl
Private WithEvents img As Image
Private WithEvents lbl As Label
Private WithEvents lin As Line
Private WithEvents Lst As ListBox
Private WithEvents frm As ObjectFrame
Private WithEvents optb As OptionButton
Private WithEvents optg As OptionGroup
Private WithEvents pg As Page
Private WithEvents pgb As PageBreak
Private WithEvents Rec As Rectangle
Private WithEvents sfm As SubForm
Private WithEvents tctl As TabControl
Private WithEvents txt As TextBox
Private WithEvents tgl As ToggleButton
Property Set ctl(PassedControl As Control)
Set m_PassedControl = PassedControl
Select Case TypeName(PassedControl)
Case "Attachment"
Set atch = PassedControl
Case "BoundObjectFrame"
Set bfrm = PassedControl
Case "CheckBox"
Set chk = PassedControl
Case "ComboBox"
Set cbo = PassedControl
Case "CommandButton"
Set btn = PassedControl
Case "CustomControl"
Set cctl = PassedControl
Case "Image"
Set img = PassedControl
Case "Label"
Set lbl = PassedControl
Case "Line"
Set lin = PassedControl
Case "ListBox"
Set Lst = PassedControl
Case "ObjectFrame"
Set frm = PassedControl
Case "OptionButton"
Set optb = PassedControl
Case "OptionGroup"
Set optg = PassedControl
Case "Page"
Set pg = PassedControl
Case "PageBreak"
Set pgb = PassedControl
Case "Rectangle"
Set Rec = PassedControl
Case "SubForm"
Set sfm = PassedControl
Case "TabControl"
Set tctl = PassedControl
Case "TextBox"
Set txt = PassedControl
Case "ToggleButton"
Set tgl = PassedControl
End Select
End Property
At the top of the Main Form module place the following code.
Public collControls As Collection
Public cMultipleControls As clsMultipleControls
In the Load event of the Main Form place the following code.
GetCollection Me
At the bottom of the Main Form code place the following recursive public subroutine:
Public Sub GetCollection(frm As Form)
Dim ctl As Control
On Error Resume Next
Set collControls = collControls
On Error GoTo 0
If collControls Is Nothing Then
Set collControls = New Collection
End If
For Each ctl In frm.Controls
If ctl.ControlType = acSubform Then
GetCollection ctl.Form
Else
Set cMultipleControls = New clsMultipleControls
Set cMultipleControls.ctl = ctl
collControls.Add cMultipleControls
End If
Next ctl
end sub
I'd advise giving each control in the form and its subforms a unique name so you can easily utilize the Select statement based on the control name to effectuate processing control in each class module event. For example, each textbox change event will be sent to the txt_change event in the class module where you can use the m_PassedControl.name property in a select statement to direct which code will be executed on the passed control.
The select event is quite useful if you have multiple controls that will receive the same post entry processing.
I use the Main Form Load event rather than the Activate event because a popup form (and its subforms) do not fire the Activate or Deactivate events.
One can also pass the m_PassedControl on to a subroutine in a regular module if you have you have some lengthy processing to accommodate.
Unfortunately, Access does not automatically fire VBA events unless you actually set the event up in the VBA module. So if you want to use a textbox change event you have to make sure the textbox change event is actually set up in applicable vba module. You don't need to add any code to the event, but the empty event must be there or the event and its class module equivalent will not fire. If anyone knows of a work around for this I'd be glad to hear about it.
I found this basic class module structure in an Excel userform code example at http://yoursumbuddy.com/userform-event-class-multiple-control-types/. It's a flexible structure. I have created versions that work with Excel userforms, Excel worksheets with activex controls, and now for Access forms.
Followup Note: The above code works fine with 64 bit Access 2013 on 64 bit Windows 10. But it fails on 64 bit Access 2013 on 64 bit Windows 7 when you try to close the main form. The solution is to move the following code from the main form to a VBA module.
Public collControls As Collection
Public cMultipleControls As clsMultipleControls

MEF part unable to import Autofac autogenerated factory

This is a (to me) pretty weird problem, because it was already running perfectly but went completely south after some unrelated changes.
I've got a Repository which imports in its constructor a list of IExtensions via Autofacs MEF integration. One of these extensions contains a backreference to the Repository as Lazy(Of IRepository) (lazy because of the circular reference that would occur).
But as soon as I try to use the repository, Autofac throws a ComponentNotRegisteredException with the message "The requested service 'ContractName=Assembly.IRepository()' has not been registered."
That is, however, not really correct, because when I break right after the container-build and explore the list of services, it's there - Exported() and with the correct ContractName.
I'd appreciate any help on this...
Michael
[Edit] Here's a thinned-out version of the code:
Repository
Public Class DocumentRepository
Implements IDocumentRepository
Private _extensions As IEnumerable(Of IRepositoryExtension)
Public Sub New(ByVal extensions As IEnumerable(Of IRepositoryExtension))
_extensions = extensions
End Sub
Public Sub AddDocument(ByVal document As Contracts.IDocument) Implements Contracts.IDocumentRepository.AddDocument
For Each extension In _extensions
extension.OnAdded(document.Id)
Next
End Sub
End Class
Plugin
<Export(GetType(IRepositoryExtension))>
<PartCreationPolicy(ComponentModel.Composition.CreationPolicy.Shared)>
Public Class PdfGenerator
Implements IRepositoryExtension
Private _repositoryFactory As Lazy(Of IDocumentRepository)
Public Sub New(ByVal repositoryFactory As Lazy(Of IDocumentRepository))
_repositoryFactory = repositoryFactory
End Sub
Public Sub CreatePdf(ByVal id As Guid) Implements Contracts.IRepositoryExtension.OnAdded
Dim document = _repositoryFactory.Value.GetDocumentById(id)
End Sub
End Class
Bootstrapper
Public Class EditorApplication
Inherits System.Web.HttpApplication
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim builder As New ContainerBuilder()
Dim catalog1 As New TypeCatalog(GetType(DataRepositoryScheme))
Dim catalog2 As New DirectoryCatalog(HttpContext.Current.Server.MapPath("/Plugins"))
builder.RegisterComposablePartCatalog(New AggregateCatalog(catalog1, catalog2))
builder.RegisterType(Of DocumentRepository).As(Of IDocumentRepository).SingleInstance().Exported(Function(x) x.As(Of IDocumentRepository)())
AutofacServiceHostFactory.Container = builder.Build()
End Sub
End Class
Ah immediately after I posted that last comment I think I figured it out:
The requested service 'ContractName=ConsoleApplication7.IDocumentRepository()'
has not been registered.
Note that there is a pair of parentheses after the contract name - this is because the contract is a function, i.e., this message was produced by the following constructor, which is slightly different from the one in your sample:
Public Sub New(ByVal repositoryFactory As Func(Of IDocumentRepository))
_repositoryFactory = repositoryFactory
End Sub
Note the 'Func' in there. MEF, unlike Autofac, does not regard Func as a special type and so will not translate this into the same contract as for Lazy.
If you want to provide a Func to a MEF component, you need to export it as a Func from Autofac. This is a bit tricky:
builder.RegisterType(Of DocumentRepository).As(Of IDocumentRepository)
builder.Register(Function(c) c.Resolve(Of Func(Of IDocumentRepository))) _
.As(New UniqueService()) _
.Exported(Function(x) x.As(Of Func(Of IDocumentRepository))
You may need to play with the syntax a bit, my VB.NET is fairly shaky.
My guess is that there are stale binaries in your /Extensions directory that are interfering with debugging this.
Hope this is on the mark!
Nick

Inner Transactionscope error: "Communication with the underlying transaction manager has failed"

I am not sure I am doing any of this correctly. Is it because I am opening two connections? I am closing them regardless of errors. I did try putting in some inner transaction scopes and setting the second one to RequiresNew. The two methods are independent of each other, however, if one fails I need them both to rollback. I may have to modify how I am creating and closing the connections, I feel. Any thoughts? Here is some example code of what I am doing:
Public Sub TransMethod()
Using sTran As New Transactions.TransactionScope
factory1.UpdateMethod(someObject1)
facotry2.insert(someobject2)
sTran.Complete()
End Using
End Sub
Public Class factory1
Public Shared Sub UpdateMethod(obj)
dim someSQLParams....
DataAcces.ExecuteNonQuery(command,someSQLParams)
End Sub
End Class
Public Class factory2
Public Shared Sub Insert(obj)
dim someSQLParams....
DataAcces.ExecuteNonQuery(command,someSQLParams)
End Sub
End Class
Public Function ExecuteNonQuery(ByVal spname As String, _
ByVal ParamArray parameterValues() As Object) As Object
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand = Nothing
Dim res As Object = Nothing
Try
connection = New SqlConnection(_connectionString)
command = New SqlCommand(spname, connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddRange(parameterValues)
connection.Open()
command.ExecuteNonQuery()
res = command.Parameters(command.Parameters.Count - 1).Value
Catch ex As Exception
CreateDataEntry(ex, WriteType.ToFile, spname)
If Not (transaction Is Nothing) Then
transaction.Rollback()
End If
Finally
If Not (connection Is Nothing) AndAlso _
(connection.State = ConnectionState.Open) Then _
connection.Close()
If Not (command Is Nothing) Then command.Dispose()
End Try
Return res
End Function
Whenever you open more than 1 connection using TransactionScope, it changes from a normal transaction against sql server to a distributed transaction, which requires setting up the MSDTC.
That will happen even if the connections have the same connection string, which is one of the "by design" issues. I haven't followed up if it remains the same on .net 3.5+