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

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

Related

how to open EntityConnection without connection string

I need to open the connection for Entity Framework without a connection string.
Due to a security layer that we are using I'm, we don't allow to connect to SQL Server using connection string, So we have a DLL that returns an opened SqlConnection.
EF version: 6.2.0
Error:
MetadataWorkspace must have EdmItemCollection pre-registered.
I tried to give the entityConnection as SqlConnection but I get an error.
Sample code:
Public Shared Function getEntityConnection() As EntityConnection
Dim workspace As New MetadataWorkspace()
Return New EntityClient.EntityConnection(workspace, AppCommon.AppFunctions.AppGetSQLCon(True))
End Function
AppCommon.AppFunctions.AppGetSQLCon(True) is the function which returns the SqlConnection instance.
But it's not working, does anyone have a solution for this issue?
Finally I found the solution for connecting the entityframework without a connection string, So what you need to is the following:
change the constructor of the entity `DbContext' to recive the connection from a function like this:
Public Sub New()
MyBase.New(getEntityConnection(), False)
End Sub
Then inside that function return an entity-connection object from an open sqlconnection obbject as the following:
Public Shared Function getEntityConnection() As EntityConnection
Dim workspace As New MetadataWorkspace(New String() {"res://*/"}, New Assembly() {Assembly.GetExecutingAssembly()})
Return New EntityClient.EntityConnection(workspace, getSqlConnectionObject())
End Function
Now your entityframework is connected to the database without a connection string

How to set "Application Name" in ADODB connection string

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

Connection string for ms Access in Ms winforms application

Everything is perfect in this connection string according to my knowledge.But its not working fine.I'll be very thankful if someone helps me out to sort out this issue.Thanks
string constr = "**Provider=Microsoft.ACE.OLEDB.4.0; Data Source=Data Source=F:/Database1.accdb;Persist Security Info=False**";
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(constr);
Your current connection string has multiple issues. Try this instead:
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database1.accdb;Persist Security Info=False";

It's possible to use OleDbConnections with the Script Component?

I'm building an ssis package and I wish to use an existing OleDbConnection inside the Script Component. Here is my code:
public override void AcquireConnections(object Transaction)
{
base.AcquireConnections(Transaction);
cm = this.Connections.Connection;
con = (OleDbConnection)cm.AcquireConnection(Transaction);
MessageBox.Show(con.ToString());
}
When I close BIDS, i get the following message:
"System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.OleDb.OleDbConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."
The same code works fine with an Ado.Net connection. Can I use OleDbConnection here or Script Component only supports Ado.Net?
Thanks in advance.
As mentioned in the MSDN
You cannot call the AcquireConnection method of connection managers that return unmanaged objects, such as the OLE DB connection manager and the Excel connection manager, in the managed code of a Script task.
You need to use the ADO.NET connection manager if you want to use Aquire Connection method
in order to use OLEDB connection add a reference to Microsoft.SqlServer.DTSRuntimeWrap and try the below code
ConnectionManager cm = Dts.Connections["oledb"];
IDTSConnectionManagerDatabaseParameters100 cmParams =
cm.InnerObject as IDTSConnectionManagerDatabaseParameters100;
OleDbConnection conn = cmParams.GetConnectionForSchema() as OleDbConnection;
MSDN Link
Just in case someone googled this and couldn't find a real solution, you have to override the AcquireConnections, PreExceute and ReleaseConnections methods in order to use an OleDbConnection. The trick is the ConnectionString property:
OleDbConnection con;
OleDbCommand cmd;
IDTSConnectionManager100 connMgr;
/*Here you prepare the connection*/
public override void AcquireConnections(object Transaction)
{
base.AcquireConnections(Transaction);
connMgr = this.Connections.YourConnName;
con = new OleDbConnection(connMgr.ConnectionString);
}
/*Here you prepare the sql command and open the connection*/
public override void PreExecute()
{
base.PreExecute();
cmd = new OleDbCommand("Some Select", con);
cmd.CommandType = CommandType.Text;
con.Open();
}
/*Here you execute your query for each input row*/
public override void Entrada0_ProcessInputRow(Entrada0Buffer Row)
{
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
/*Do your stuff*/
}
}
/*And here you release the connection*/
public override void ReleaseConnections()
{
base.ReleaseConnections();
connMgr.ReleaseConnection(con);
}
HTH
Thanks praveen.
I found the relevant part in your link:
"If you must call the AcquireConnection method of a connection manager that returns an unmanaged object, use an ADO.NET connection manager. When you configure the ADO.NET connection manager to use an OLE DB provider, it connects by using the .NET Framework Data Provider for OLE DB. In this case, the AcquireConnection method returns a System.Data.OleDb.OleDbConnection instead of an unmanaged object. To configure an ADO.NET connection manager for use with an Excel data source, select the Microsoft OLE DB Provider for Jet, specify an Excel file, and enter Excel 8.0 (for Excel 97 and later) as the value of Extended Properties on the All page of the Connection Manager dialog box."
Thanks!

Need to change connection string on client computer at run time

Please see the pic. and advise how I can change this connection string at run time. This is going to be on Client's computer and my application will need to change the name of computer after user enters it.
Thanks!
Just on the top of my head..
Dim adapter As New dbTestSharingDataSet.tblTestTableAdapter
Dim conn As New SqlConnection()
conn.ConnectionString = MyConnectionManager.ConnectionString
adapter.Connection = conn
Dim table As DataTable = adapter.GetData()

Resources