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
Related
I have developed a program for a user to search a database. I did this on my local PC and it worked fine. I move the app to the server where it would used, changed the Data Source and I get an error (below). I used the name of the Server Name shown on the start up of SQL2008 R2 as the Data Source, which is the same thing I did on my local PC. I built a simple program just to test the Connection (below). I have tried different things, read everything I could find on the error, but no good.
Here is the code I'm using to test the connection:
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MyConnectionString As String = " Data Source=MenClub02;Database=eCom_Email;Integrated Security=SSPI"
Using connection As New SqlConnection(MyConnectionString)
connection.Open()
MsgBox("State: {0}", connection.State)
MsgBox("ConnectionString: {0}", connection.ConnectionString)
End Using
End Sub
End Class
The following error shows up on the Using connection As New SqlConnection(MyConnectionString) line:
System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
Source=System.Data
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()
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
I found this code on the web
Imports System
Imports System.Collections.Specialized
Namespace Williablog.Net.Examples.Providers
Public Class SqlMembershipProvider
Inherits System.Web.Security.SqlMembershipProvider
Public Overrides Sub Initialize(ByVal name As String, ByVal config As System.Collections.Specialized.NameValueCollection)
' intercept the setting of the connection string so that we can set it ourselves...
Dim specifiedConnectionString As String = config.Item("connectionStringName")
config.Item("connectionStringName") = GetYourRunTimeConnectionStringNAme(specifiedConnectionString)
' Pass doctored config to base classes
MyBase.Initialize(name, config)
End Sub
End Class
End Namespace
I think it will solve my problem.
I need to encrypt my connection string in the web.config
I am using MS default Membership provider
The login mechanism "Membership.ValidateUser(UsernameTextbox.Text,
passwordtext)) doesn't allow me to change the connection string and
it uses the one in the web.config.
Can i use the code above to change the connection string so that I
can decrypt it first before Validate User runs?
if yes, how do I use the code above in my code?
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!