Avatar of Chris120590
Chris120590

asked on 

How to change database in code?

I have this sample code I am trying to use to build a database where I can upload .pdf files.  I want to change this code so that it will work with my ASPNETDB but I can't figure it out.  I believe this is in mySQL and I use SQL Server I am unsure how to change the connection.  This code wants to connect to the original database Files.mdf but I want it to connect to ASPNETDB.mdf.  Anybody know how to do this?  I would greatly appreciate the help thanks.

P.S The connection needs to change I am maintaining the table used in Files.mdf I just duplicated it to ASPNETDB
From File.vb
------------------------------------------------------------------------
Imports System
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
 
''' <summary>
''' The File class abstracts behavior for uploaded files that are stored in a datastore.
''' It allows you to save an uploaded file in the datastore and retrieve it again.
''' </summary>
<DataObject()> _
Public Class File
 
#Region "Private Variables"
 
  Private _id As Guid
  Private _fileUrl As String
  Private _fileData As Byte()
  Private _contentType As String
  Private _originalName As String
  Private _dateCreated As DateTime
  Private _containsFile As Boolean
 
#End Region
 
#Region "Public Properties"
  ''' <summary>
  ''' Gets the unique id of the uploaded file.
  ''' This ID is used as the file name when files are stored in the file system.
  ''' </summary>
  Public ReadOnly Property Id() As Guid
    Get
      Return _id
    End Get
  End Property
 
  ''' <summary>
  ''' Gets the date and time the file was uploaded.
  ''' </summary>
  Public ReadOnly Property DateCreated() As DateTime
    Get
      Return _dateCreated
    End Get
  End Property
 
  ''' <summary>
  ''' Gets the content type of the file.
  ''' </summary>
  Public ReadOnly Property ContentType() As String
    Get
      Return _contentType
    End Get
  End Property
 
  ''' <summary>
  ''' Gets the original name of the file.
  ''' </summary>
  Public ReadOnly Property OriginalName() As String
    Get
      Return _originalName
    End Get
  End Property
 
  ''' <summary>
  ''' Gets the virtual URL of the file.
  ''' When this property does not contain data, then <see cref="FileData"/> contains
  ''' a byte array with the actual file.
  ''' </summary>
  Public ReadOnly Property FileUrl() As String
    Get
      Return _fileUrl
    End Get
  End Property
 
  ''' <summary>
  ''' Gets the file data.
  ''' When this property does not contain data, then <see cref="FileUrl"/> contains
  ''' the virtual path to the file starting from the Uploads folder.
  ''' </summary>
  Public ReadOnly Property FileData() As Byte()
    Get
      Return _fileData
    End Get
  End Property
 
  ''' <summary>
  ''' Gets a value indicating whether this instance contains the actual file data.
  ''' When ContainsFile is true, it means the actual file is held in <see cref="FileData"/>.
  ''' When ContainsFile is false, then <see cref="FileUrl"/> contains the virtual path
  ''' to the file on disk.
  ''' </summary>
  Public ReadOnly Property ContainsFile() As Boolean
    Get
      Return _containsFile
    End Get
  End Property
#End Region
 
#Region "Public Methods"
  ''' <summary>
  ''' Gets a file from the datastore.
  ''' </summary>
  ''' <param name="fileId">The ID of the file.</param>
  Public Shared Function GetItem(ByVal fileId As Guid) As File
    Dim myFile As File = Nothing
    Using mySqlConnection As SqlConnection = New SqlConnection(AppConfiguration.ConnectionString)
      Dim myCommand As SqlCommand = New SqlCommand("sprocFilesSelectSingleItem", mySqlConnection)
      myCommand.CommandType = CommandType.StoredProcedure
      Dim prmId As SqlParameter = New SqlParameter("@id", SqlDbType.UniqueIdentifier)
      prmId.Value = fileId
      myCommand.Parameters.Add(prmId)
      mySqlConnection.Open()
      Using myReader As SqlDataReader = myCommand.ExecuteReader()
        If myReader.Read() Then
          myFile = New File(myReader)
        End If
        myReader.Close()
      End Using
      mySqlConnection.Close()
    End Using
    Return myFile
  End Function
 
  ''' <summary>
  ''' Saves a file to the database.
  ''' </summary>
  ''' <returns>Returns true when the file was stored succesfully, or false otherwise.</returns>
  Public Function Save() As Boolean
    Return Save(DataStoreType.Database, String.Empty)
  End Function
 
  ''' <summary>
  ''' Saves a file to the file system.
  ''' This method also saves the meta data of the file to the database.
  ''' </summary>
  ''' <param name="filePath">The location and name of the file that is to be saved.</param>
  ''' <returns>
  ''' Returns true when the file was stored succesfully, or false otherwise.
  ''' </returns>
  Public Function Save(ByVal filePath As String) As Boolean
    Return Save(DataStoreType.FileSystem, filePath)
  End Function
 
  ''' <summary>
  ''' Saves a file to the database and optionally to disk.
  ''' </summary>
  ''' <returns>Returns true when the file was stored succesfully, or false otherwise.</returns>
  Private Function Save(ByVal dataStoreType As DataStoreType, ByVal filePath As String) As Boolean
    Using mySqlConnection As SqlConnection = New SqlConnection(AppConfiguration.ConnectionString)
      Dim myCommand As SqlCommand = New SqlCommand("sprocFilesInsertSingleItem", mySqlConnection)
      myCommand.CommandType = CommandType.StoredProcedure
      Dim prmId As SqlParameter = New SqlParameter("@id", SqlDbType.UniqueIdentifier)
      prmId.Value = Id
      myCommand.Parameters.Add(prmId)
      Dim prmFileUrl As SqlParameter = New SqlParameter("@fileUrl", SqlDbType.NVarChar, 255)
      If dataStoreType = dataStoreType.FileSystem Then
        prmFileUrl.Value = FileUrl
      Else
        prmFileUrl.Value = DBNull.Value
      End If
      myCommand.Parameters.Add(prmFileUrl)
      Dim prmFileData As SqlParameter = New SqlParameter("@fileData ", SqlDbType.VarBinary)
      If dataStoreType = dataStoreType.Database Then
        prmFileData.Value = FileData
        prmFileData.Size = FileData.Length
      Else
        prmFileData.Value = DBNull.Value
      End If
      myCommand.Parameters.Add(prmFileData)
      Dim prmOriginalName As SqlParameter = New SqlParameter("@originalName", SqlDbType.NVarChar, 50)
      prmOriginalName.Value = OriginalName
      myCommand.Parameters.Add(prmOriginalName)
      Dim prmContentType As SqlParameter = New SqlParameter("@contentType", SqlDbType.NVarChar, 50)
      prmContentType.Value = ContentType
      myCommand.Parameters.Add(prmContentType)
      mySqlConnection.Open()
      Dim result As Boolean = myCommand.ExecuteNonQuery() > 0
      mySqlConnection.Close()
      If dataStoreType = dataStoreType.FileSystem Then
        Const myBufferSize As Integer = 1024
        Dim myInputStream As Stream = New MemoryStream(FileData)
        Dim myOutputStream As Stream = System.IO.File.OpenWrite(filePath)
        Dim buffer As Byte() = New Byte(myBufferSize) {}
        Dim numbytes As Integer = myInputStream.Read(buffer, 0, myBufferSize)
        While (numbytes) > 0
          myOutputStream.Write(buffer, 0, numbytes)
          numbytes = myInputStream.Read(buffer, 0, myBufferSize)
        End While
        myInputStream.Close()
        myOutputStream.Close()
      End If
      Return result
    End Using
  End Function
 
#End Region
 
#Region "Constructor(s)"
  ''' <summary>
  ''' Initializes a new instance of the <see cref="File"/> class with the data from the SqlDataReader.
  ''' </summary>
  ''' <param name="myReader">A SqlDataReader that contains the data for this file.</param>
  Public Sub New(ByVal myReader As SqlDataReader)
    _id = myReader.GetGuid(myReader.GetOrdinal("Id"))
    _dateCreated = myReader.GetDateTime(myReader.GetOrdinal("DateCreated"))
    _originalName = myReader.GetString(myReader.GetOrdinal("OriginalName"))
    _contentType = myReader.GetString(myReader.GetOrdinal("ContentType"))
    If Not myReader.IsDBNull(myReader.GetOrdinal("FileData")) Then
      _fileData = DirectCast(myReader(myReader.GetOrdinal("FileData")), Byte())
      _containsFile = True
    Else
      _fileUrl = myReader.GetString(myReader.GetOrdinal("FileUrl"))
      _containsFile = False
    End If
  End Sub
 
  ''' <summary>
  ''' Initializes a new instance of the File class with the data from the incoming parameters.
  ''' </summary>
  ''' <param name="contentType">The content type of the file, like image/pjpeg or image/gif.</param>
  ''' <param name="originalName">The original name of the uploaded file.</param>
  ''' <param name="fileData">A byte array with the actual file data.</param>
  Public Sub New(ByVal contentType As String, ByVal originalName As String, ByVal fileData As Byte())
    Me._id = Guid.NewGuid()
    Me._contentType = contentType
    Me._fileData = fileData
    Me._originalName = originalName
    Dim extension As String = Path.GetExtension(_originalName)
    Dim fileName As String = Me._id.ToString() + extension
    Me._fileUrl = fileName
  End Sub
#End Region
 
End Class
------------------------------------------------------------------------
 
From AppConfiguration.vb
------------------------------------------------------------------------
Imports System
Imports System.Configuration
 
''' <summary>
''' The AppConfiguration contains static read-only properties that map to settings in the web.config file.
''' </summary>
Public Class AppConfiguration
 
  ''' <summary>
  ''' Gets the type of data store to use. Valid options come from the <see cref="DataStoreType"/> 
  ''' enumeration and currently include Database and FileSystem.
  ''' </summary>
  ''' <value>The type of the data store.</value>
  Public Shared ReadOnly Property DataStoreType() As DataStoreType
    Get
      Return DirectCast([Enum].Parse(GetType(DataStoreType), ConfigurationManager.AppSettings.[Get]("DataStoreType"), True), DataStoreType)
    End Get
  End Property
 
  ''' <summary>
  ''' Gets the virtual path to the Uploads folder.
  ''' </summary>
  Public Shared ReadOnly Property UploadsFolder() As String
    Get
      Return ConfigurationManager.AppSettings.Get("UploadsFolder")
    End Get
  End Property
 
  ''' <summary>
  ''' Gets the connection string for the application.
  ''' </summary>
  ''' <value>The connection string.</value>
  Public Shared ReadOnly Property ConnectionString() As String
    Get
      Return ConfigurationManager.ConnectionStrings("DefaultConnectionString").ConnectionString
    End Get
  End Property
End Class

Open in new window

.NET ProgrammingVisual Basic.NETMicrosoft SQL Server

Avatar of undefined
Last Comment
Geert G
ASKER CERTIFIED SOLUTION
Avatar of Geert G
Geert G
Flag of Belgium image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Chris120590
Chris120590

ASKER

Where would I insert this?  I don't really see where it would be replaced, I can't seem to find where the other database connection is.
Avatar of Geert G
Geert G
Flag of Belgium image

B ?
you place it where you want to change the database
on the SQL Server instance you can have more than 1 database

to switch back do the same
use original_db

since you are allready connected to the database
you don't need a other connection string
providing the user from the first connection also has access to the secondary database
Microsoft SQL Server
Microsoft SQL Server

Microsoft SQL Server is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into editions to distinguish between product functionality. Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning.

171K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo