How to set "Application Name" in ADODB connection string - sql-server

In .NET I simply use Application Name = MyApp inside the connection string, but when using ADO connection through VBA the Activity Monitor of the SQL Server Management Studio always shows Microsoft Office 2010 in Processes on the Application column no matter what name I set on the VBA code.
conn.ConnectionString = "UID=" & UID & ";PWD=" & PWD & ";DSN=" & DSN & _
";Application Name = MyApp"
How can I set the application name for monitoring purposes?

Ahh I see VBA connection string doesn't support the Application Name attribute. It simply isn't being recognized when used within VBA. The only way I can think of solving this at the moment it's to return an ADODB.Connection object from a COM C# library.
Your own COM library would return an ADODB.Connection object with a predefined connection string which seem to work in .NET. You will be connecting to the database using a VBA ADODB.Connection object but with a substituted object reference. Instead of
Set cn = new ADODB.Connection you will use a GetConection() method exposed by your own library.
Dim cn as ADODB.Connection
Set cn = yourCOMlibrary.GetConnection
here are the steps
Download and install Visual Studio Express for Windows (FREE)
Open it as Administrator and create a New Project. Select Visual C# then Class Library and rename it to MyConnection
In the Solution Explorer, rename Class1.cs to ServerConnection.cs
Right click your MyConnection project in the Solution Explorer and select Add Reference
Type activeX in the search box and tick the Microsoft ActiveX Data Objects 6.1 Library
Copy and paste the below code into the ServerConnection.cs completely replacing whatever is in the file.
using System;
using System.Runtime.InteropServices;
using System.IO;
using ADODB;
namespace MyConnection
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("32A5A235-DA9F-47F0-B02C-9243315F55FD")]
public interface INetConnection
{
Connection GetConnection();
void Dispose();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("4E7C6DA2-2606-4100-97BB-AB11D85E54A3")]
public class ServerConnection : INetConnection, IDisposable
{
private Connection cn;
private string cnStr = "Provider=SQLOLEDB; Data Source=SERVER\\DB; Initial Catalog=default_catalog; User ID=username; Password=password;Application Name=MyNetConnection";
public Connection GetConnection()
{
cn = new Connection();
cn.ConnectionString = cnStr;
return cn;
}
public void Dispose()
{
cn = null;
GC.Collect();
}
}
}
Locate the cnStr variable in the code and UPDATE your connection string details.
Note: if you are unsure about the connection string you should use see ALL CONNECTION STRINGS
Click on TOOLs in Visual Studio and CREATE GUID
Replace the GUIDs with your own and remove the curly braces so they are in the same format as the ones you see now from the copied code
Right click MyConnection in the Solution Explorer and select Properties.
Click the Application tab on the left side, then Assembly Info and tick Make Assembly COM-Visible
Click the *Build* from the menu on the left and tick Register For COM Interop
Note: If you are developing for 64-bit Office then make sure you change the Platform Target on the Build menu to x64! This is mandatory for 64-bit Office COM libraries to avoid any ActiveX related errors.
Right click MyConnection in the Solution Explorer and select Build from the menu.
If everything went OK then your MyConnection.dll and MyConnection.tlb should be successfully generated. Go to this path now
C:\Users\username\desktop\
or wherever you saved them
and you should see your files.
Now open Excel and go to VBE. Click Tools and select References.
Click the Browse button and navigate to the MyConnection.tlb.
Also, add references to Microsoft ActiveX Object 6.1 Library - this is so you can use ADODB library.
Now right click anywhere in the Project Explorer window and Insert a new Module
copy and paste the below code to it
Option Explicit
Sub Main()
Dim myNetConnection As ServerConnection
Set myNetConnection = New ServerConnection
Dim cn As ADODB.Connection
Set cn = myNetConnection.GetConnection
cn.Open
Application.Wait (Now + TimeValue("0:00:10"))
cn.Close
Set cn = Nothing
myNetConnection.Dispose
End Sub
Open SQL Server Management Studio, right click the server and select Activity Monitor
dont close this window
Go back to Excel and hit F5 or hit the green play button on the ribbon.
now switch back to SSMS ( SQL Server Management Studio )
and wait for your custom connection name to appear! :)
Here we go! That was easy, wasn't it? :)
This is what is happening.
You are returning an ADODB Connection object from you C# COM library by using myNetConnection.GetConnection function
Dim myNetConnection As ServerConnection
Set myNetConnection = New ServerConnection
Dim cn As ADODB.Connection
Set cn = myNetConnection.GetConnection
It's almost like saying Set cn = new ADODB.Connection but with predefined connection string which you did in your C# code.
You can use the cn object like a normal ADODB.Connection object within VBA now.
Remember to always .Close() the ADODB.Connection. A good programmers practice is to always close anything you open - streams, connections, etc.
You can rely on the Garbage Collector to free references/ memory but I also wrote a Dispose() method for you so you can force the GC to run. You can do that to immediately get rid of the Connection so it does not hang in the SSMS as opened.
Remember to use myNetConnection.Dispose along with the cn.Close and you'll be fine.
Note:
This is how I would do it if any one thinks this is wrong or needs to be updates (as being unstable or unsafe) please leave a comment.
Well, I hope this will be helpful to anyone in the future :)

The correct keyword to set the application name in an ADODB connection string in VBA is APP, not Application Name.
Example connection string, copied from an MS Access app I'm working on:
DRIVER={SQL Server};SERVER=xxxx;DATABASE=xxxx;Trusted_Connection=Yes;APP=xxxx

Related

Using SQL Server Authentication to connect to SSRS from a WinForms Application

I'm busy testing SSRS to see if it's a viable alternative to our current reporting solution. I've set up SSRS on my local machine and have developed a working report using SQL Server Report Builder. Now what I'm trying to do is to call the report from within a WinForms application and display it in a ReportViewer control. The problem is that I've set up SQL Server to use SQL Server Authentication and I'm struggling to figure out how to connect to it programmatically.
The code I've pieced together so far looks like this:
Imports Microsoft.Reporting.WinForms
Public Class frmMain
Public v_report_name As String = "TestReport"
Public v_report_server As String = "http://elnah-ict-dt006:80"
Public v_report_path As String = "/reports_SSRS/"
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'create parameter array
Dim paramlist As New List(Of Microsoft.Reporting.WinForms.ReportParameter)
'create a specific parameter required by the report
Dim param1 As New Microsoft.Reporting.WinForms.ReportParameter("ClientID")
'add values to the parameter here we use a variable that holds the parameter value
param1.Values.Add("0279")
'add parameter to array
paramlist.Add(param1)
'Set the processing mode for the ReportViewer to Remote
ReportViewer1.ProcessingMode = ProcessingMode.Remote
'use the serverreport property of the report viewer to select a report from a remote SSRS server
ReportViewer1.ServerReport.ReportServerUrl = New System.Uri(v_report_server)
ReportViewer1.ServerReport.ReportPath = v_report_path & v_report_name
'select where the report should be generated with the report viewer control or on the report server using the SSRS service.
'Me.ReportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote
'add the parameterlist to the viewer
ReportViewer1.ServerReport.SetParameters(paramlist)
Me.ReportViewer1.RefreshReport()
End Sub
End Class
When it hits the SetParameters line towards the bottom, it gets the following error message:
Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.MissingEndpointException
HResult=0x80131500
Message=The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
Source=Microsoft.ReportViewer.WinForms
I've tried to find examples of how to set the username and password but from what I can tell, most examples are focused on using Windows Authentication. I've tried the following line but it doesn't work:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials("SA", "mypassword")
I haven't worked in VB.NET for ages so please excuse any obvious errors.
Here's some code from a Web Forms project I was part of the team for recently:
private void SetCredentials()
{
var userName = ConfigurationManager.AppSettings["SSRSUserName"];
var passwordEncrypted = ConfigurationManager.AppSettings["SSRSUserPasswordEncrypted"];
var passwordPlainText = SI.Crypto3.Crypto.Decrypt(passwordEncrypted, PASSPHRASE);
var domain = ConfigurationManager.AppSettings["SSRSUserDomain"];
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passwordPlainText) && !string.IsNullOrEmpty(domain))
{
this.EventsHubReportViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials(userName, passwordPlainText, domain);
}
}
That's C# but hopefully you can see that the important part is that last line. I think that the equivalent in your case should be:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials(userName, password, domain)
The domain value can be an empty String if your on the same domain as the server.
EDIT:
I looked more closely and the ReportServerCredentials class that code is using is one of our own. In your case, you can use the Microsoft.ReportViewer.WinForms.ReportServerCredentials class, which I don't think has a constructor like that. Looking at the documentation for the NetworkCredentials property of that type indicates that you need to do this:
Dim credentials As New NetworkCredential(userName, password, domain)
ReportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = credentials

vb.net: Checking SQL Server status

Sometimes when my customers turn on or restart their computer, and open my vb.net application directly, the application opens before SQL Server has started completely.
This results in many unexpected behaviors. To avoid this situation, I need to start a splash screen and check the SQL Server state within it, and only when SQL Server state indicates that it is loaded completely, can I run the whole application.
The question is: how to check the SQL Server state, whether it is finished loading or not? The whole SQL Server, not the database.
You can instantiate a timer in your splash form that checks if it can log into the database every one second (or whatever interval you like). I'd invoke the splash form as modal so the calling app can't continue until the splash form has detected the connection and closed itself.
At the very least you need the server name to check the connection for. If it is using a named instance then the server name should also include the instance name in the format "myserver\myinstance".
I've encapsulated the connection checking logic in the 3 overloaded functions IsConnected. You can use these functions in your splash form to check connection from the timer tick. (Each depends on the next). You can use whichever function overload is suitable based on the input items you have available.
For the first overload, if the app is running under a Windows security context that can connect to the db server then you don't need to provide the username and password (pass as empty string), otherwise you need to provide those credentials needed to login to the db server. Or you can provide your own connection string or connection object for the other overloads.
(code within the splash form)...
Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
If Me.IsConnected("(local)\SQL2008R2", "", "") Then Me.Close()
End Sub
Public Function IsConnected(ServerName As String, UserID As String, Password As String) As Boolean
Dim connStr As String = String.Format("Data Source={0}", ServerName)
If Not String.IsNullOrEmpty(UserID) Then
connStr &= String.Format(";User ID={0};Password={1}", UserID, Password)
Else
connStr &= ";Integrated Security=True"
End If
Return IsConnected(connStr)
End Function
Public Function IsConnected(Connection As String) As Boolean
Static conn As SqlConnection
If conn Is Nothing Then
conn = New SqlConnection(Connection)
conn.Open()
End If
Return IsConnected(conn)
End Function
Public Function IsConnected(ByRef Conn As SqlConnection) As Boolean
If Conn IsNot Nothing Then Return (Conn.State = ConnectionState.Open)
Return False
End Function
I'd invoke the splash form from the main app as a modal dialog, as such, so the app is blocked until the connection is detected.
(from the calling app form...)
frm_Splash.ShowDialog()

Visual Studio 15 (also 12) – Open Access database - "Could not find installable ISAM."

I am migrating a VB6 database app to VB 2015.
NB: The first problem was the missing ACE.OLEDB.12.0 provider. Installing the “Redistributable Access Database Engine 2010 Redistributable Engine” solved that problem on both my 32bit and 64bit computers. I am testing this code on 3 computers – Win7, Win10 and Win 10 64bit.
However, this has been followed by the “…installable ISAM” problem. The connection has been made apparently, but the program blocks on the Open() command – giving the ISAM error. Following in the simple test code:
Imports System.Data.OleDb
Public Class frmTitles
Dim BooksConnection As OleDbConnection
Private Sub frmTitles_Load (sender As Object, e As EventArgs) Handles Me.Load
'connect to books database
BooksConnection = New leDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; DataSource = d:\VB-Data\BooksDB.accdb")
'open the connection
BooksConnection.Open() ‘ Blocks here
'display state
lblState.Text = BooksConnection.State.ToString
'close the connection
BooksConnection. Close()
'display state
lblState.Text += BooksConnection.State.ToString
'dispose of the connection object
BooksConnection.Dispose()
End Sub
End Class
Please note that trying to connect an .mdb database produces the same error is produced:
BooksConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; DataSource = d:\VB-Data\Books.mdb")

Connecting to a non-local SQL Server database in VB.NET

I'm trying to connect to a SQL Server database that is not local. I have the Data Source and Initial Catalog - no issues. But need to change Integrated Security to False and insert SQL Server credentials.
Does anyone have any idea how put that in the connection string?
Also, does anyone know how to handle SecureStrings?
Here is my code so far:
Dim pwd As New SecureString("Password")
Dim cred As New SqlCredential("Username", pwd)
Dim sql As New SqlConnection("Data Source=OnlineServer;Initial Catalog=DatabaseName;Integrated Security=False")
Have a look at here: SQL Connection Strings to hopefully find which one you need. This will give you the basics.
To make the SQL account credentials confidential, you should encrypt the <connection strings> section in the web.config. to do so:
aspnet_regiis -pe "connectionStrings" -app "OnlineServer" -prov "DataProtectionConfigurationProvider"
Retrieving your connection string using ConfigurationManager will automatically decrypt the string
Dim connectionString = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Here is a Microsoft Link that explains it further.
I worked out what I needed to do and how to handle secure strings.
Here is a code snippet for anyone who struggles in the future:
Imports System.Data.SqlClient
Imports System.Net.Mail
Imports System.Security
Public Module secure
Public Function sql()
Dim pass As String = "Password"
Dim pwd As SecureString = New SecureString()
For Each ch As Char In pass
pwd.AppendChar(ch)
Next
pwd.MakeReadOnly()
Dim cred As New SqlCredential("SQL_Login", pwd)
Dim conn As New SqlConnection("Server=Database_Name;Initial Catalog=Database_Address;Integrated Security=False", cred)
Return conn
End Function
End Module
Public Class sqlCommunications
Dim sql As New SqlConnection
Dim sqlcom As New SqlCommand
Public Sub start()
sql = secure.sql
sqlcom.Connection = sql
sql.Open()
sql.Close()
End Sub
End Class

prompt for users to browse database connection if current database connection fails

I am building a data-entry program in vb.net that 5 people will share using, and I have problems setting the right database connection. It would do basic things like: pulling up the stock units, save job, load jobs operations.
The database I'm using is Access database (.mdb). This database will be located in a local server drive (mine is in Z drive) and the connection string looks like this
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb"
This works fine on my computer, but the problem is it does not work on my coworkers computer.
d (\dc-qenclosures) (Z:) is the loacation to my local server drive, but on my coworker's computer, it is set up as
d (\dc-qenclosures) (Q:).
So, whenever I open the program on my co-worker's computer, it gives me an error saying that the database Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Z:\Jimmy's Files\Quality Enclosures.mdb" does not exist (which makes sense because it is not under Z: on his computer)
I know how to use the OpenFileDialog to browse for mbd files.. but how do I set this as the new database connection?
I want to create a properties menu to set the database location.
This is the code I have so far to browse for the database file
Private Sub RadButton6_Click(sender As Object, e As EventArgs) Handles RadButton6.Click
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "mdb files (*.mdb)|*.mdb|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & openFileDialog1.FileName
con.ConnectionString = myConString
con.Open()
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
I'd second #OneFineDay's suggestion of trying the UNC path first, but to answer your main question of browsing for and saving a database path, you may want to look at storing elements of your connection string in My.Settings, so you could make the path a user-level setting. There's an MSDN article with examples here:
Using My.Settings in Visual Basic 2005
In short, you'd have the code sample you shared save the value to My.Settings.DataPath (or whatever you decide to call the setting). Then when you're connecting to the database and need the connection string, you'd make it read from My.Settings.DataPath.
Of course, that'd store your path to the database in a plain-text app.config file by default, so you'll want to be conscious of that and take appropriate steps if there are any security concerns around your app or database.

Resources