UDF Class VB.NET Reset Connection String for Entity Framework

This is a useful class I've created mixing and matching code from the web.

But basically it allows you to reset the connection string for an entity framework and save the values to the current application configuration file.

To use, something as follows

       Dim uConnection As New uCustomConnectionString

' Connection String  Name
' Server
' Database / Catalog
' Username
' Password
        uConnection.SetDatabaseConnection ("db1001229_CountersEntities", "localhost\sqlexpress", "db1001229_Counters", "sa", "password")


Imports System.Configuration
Imports System.Data.EntityClient
Imports System.Data.SqlClient

Public Class uCustomConnectionString
    Public Function SetDatabaseConnection(ByVal oConnectionString As String, ByVal ServerName As String, ByVal DatabaseName As String, ByVal NewUsername As String, ByVal NewPassword As String) As DialogResult
        Dim curConnection = ConfigurationManager.ConnectionStrings(oConnectionString).ToString()
        Dim entityBuilder As New EntityConnectionStringBuilder(curConnection)
        Dim curProviderConnString = entityBuilder.ProviderConnectionString

        ' get the current server name in the connection string.
        Dim sqlConnBuilder As New SqlConnectionStringBuilder()
        sqlConnBuilder.ConnectionString = curProviderConnString
        sqlConnBuilder.DataSource = ServerName
        sqlConnBuilder.InitialCatalog = DatabaseName
        sqlConnBuilder.UserID = NewUsername
        sqlConnBuilder.Password = NewPassword

        Dim newProviderString = sqlConnBuilder.ToString
        entityBuilder.ProviderConnectionString = newProviderString

            Using conn As EntityConnection = New EntityConnection(entityBuilder.ToString)
            End Using

            UpdateEntityConnection(oConnectionString, entityBuilder.ToString)

            MessageBox.Show("Database connection changed.")
            Return DialogResult.OK

        Catch ex As Exception
            MessageBox.Show("Database connection not changed please try again.")
            Return DialogResult.Cancel
        End Try
    End Function

    Private Sub UpdateEntityConnection(ByVal oConnectionString As String, ByVal NewConnectionString As String)
        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        config.ConnectionStrings.ConnectionStrings(oConnectionString).ConnectionString = NewConnectionString
    End Sub

End Class


Popular posts from this blog

ActiveMQ, easy to use open source message oriented middleware (MOM)

Basic Send Message to MQ with Java and IBM MQ JMS

Apache Apollo