vb.net publish application with a database - database

i want to have a built in database for my project this is what i did so far, i placed the mdb file inside the project
C:\Users\Jedi Dioh\Documents\Visual Studio 2010\Projects\kuya jake\kuya jake\bin\Debug\
i did some research this is what i did
Public Module Module1
Public path As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\"
Public source As String = "Data Source = " + path.Replace("file:\", "") + "JIMMY.MDB"
End Module
now this is the form
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:/JIMMY.mdb"
con.ConnectionString = dbProvider & source
'alternative way of connection
'Dim fldr As String
'Environment is the user profile
'fldr = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "/AddressBook.mdb"
'dbSource = "Data Source = " & fldr
con.Open()
sql = "select * from TURNING"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "RECORDS")
con.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "RECORDS"
its fine when not published but when i run the published i get this error
i don't know what to do now

You have two choices depending on whether you want changes that have been made to the database to preserved when you update the application or not.
If you do not care about the data in the database when you update the application, then you can include it in the project with a Build Action of Content and a Copy To Output Directory setting of Copy Always or Copy If Newer.
If you do care about the data in the database and don't want it to be overwritten when you update your application, then you need to store it in a well-known location (i.e. c:) and store the reference to that location in your application.

Related

How to code find and replace button using sql server 2008 & VB.Net

My app is using datagridview to display data from sqlserver.
I am working on a button code that will enable the user to find and replace the entire column. Eg find Class1 and replace with Class2.
something like UPDATE students SET class = combo1.text with combo2,text WHERE%
I am feeling too far from reality. How can this code work?
You want to set your class to the value of Combo2, where the value already matches the value of Combo1.
"UPDATE students
SET class = "+combo2.text+"
where class = "+combo1.text+" "
Copy paste this code (taken from msdn)
Public Sub ExecuteQuery(ByVal queryString As String, _
ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
End Sub
.......
and now when you need to execute you query write this
Dim cn as String
Dim UpdateQry as String
cn = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\eDataba‌​se.mdf;Integrated Security=True;User Instance=True"
UpdateQry = "Update students SET class = '" + combo2.text + "' WHERE class = '" + combo1.text + "'"
ExecuteQuery(UpdateQry, cn)
hope this helps you.
regards

public function to create and open a database connection

I have a client/server desktop application that I am having some database connection issues with on some of my clients pc's. When I wrote the app, I didn't know any better so I created and opened 1 database connection on application startup, and used that same connection all throughout the app. I know realize this is a bad idea since shaky network connections and it seems antivirus programs are causing these connection to be dropped at times, leading to some errors. I have hundreds of places in code where I need to go back and create/open/close the connection at the time they are being used.
The question is, is there any way to create a public function in which I can do just that, and then do a global find and replace to replace the connection name with the new function name?
something like:
Dim qry As NpgsqlCommand
sqlUpdateItem = "update table set field = value where id = 1"
qry = New NpgsqlCommand(sqlUpdateItem, con)
qry.ExecuteNonQuery()
to
Dim qry As NpgsqlCommand
sqlUpdateItem = "update table set field = value where id = 1"
qry = New NpgsqlCommand(sqlUpdateItem, newCon())
qry.ExecuteNonQuery()
public function newCon()
Dim con As New NpgsqlConnection(connectionString)
con.Open()
Return tcon
End Function
I tried this but no luck. I'm just looking for any possible solutions that don't involve me updating several lines of code in hundreds of places throughout my app. The nice thing is I would only need to do this for all commands, since I can pass a brand new connection into a data adapter and it will handle the opening/closing.
Here's an example of how I'd recommend you attempt it.
Enable option strict in your project. It's better to have your errors at compile time than at runtime.
Use a using statement to safely dispose of the database classes even if you get an exception.
Private _connectionString As String = "blah"
Public Function GetDbConnection() As NpgsqlConnection
Dim con As New NpgsqlConnection(_connectionString)
con.Open()
Return con
End Function
Public Sub DoMyQuery()
Using conn = GetDbConnection()
Using qry = New NpgsqlCommand("update table set field = value where id = 1", conn)
qry.ExecuteNonQuery()
End Using
End Using
End Sub

Using SSIS Environment Variables With VB Program

Good Afternoon,
I have created an SSIS Project with a single package in it. The SSIS Project and Package work as I expect when I manually executed from the server. I thought that if I set an environment variable on the server and mapped it to the project. That the project would then use those variables every time the package was executed unless otherwise told. The following code is my VB code
'VB.Net code
Imports System.Data.SqlClient
Imports Microsoft.SqlServer.Management.IntegrationServices
Imports System.Collections.ObjectModel
Public Class Form1
Private Sub StartPackageButton_Click(sender As System.Object, e As System.EventArgs) Handles StartPackageButton.Click
Try
' Connection to the database server where the packages are located
Dim ssisConnection As New SqlConnection("Data Source=" + txtServerName.Text + ";Integrated Security=SSPI;")
' SSIS server object with connection
Dim ssisServer As New IntegrationServices(ssisConnection)
' The reference to the package which you want to execute
Dim ssisPackage As PackageInfo = ssisServer.Catalogs("SSISDB").Folders("SSIS_PROJECTS").Projects("AgressoExport").Packages("File56Export.dtsx")
' Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
Dim executionParameters As New Collection(Of PackageInfo.ExecutionValueParameterSet)
' Add execution parameter to override the default asynchronized execution. If you leave this out the package is executed asynchronized
Dim executionParameter1 As New PackageInfo.ExecutionValueParameterSet
executionParameter1.ObjectType = 50
executionParameter1.ParameterName = "SYNCHRONIZED"
executionParameter1.ParameterValue = 1
executionParameters.Add(executionParameter1)
' Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
Dim executionParameter2 As New PackageInfo.ExecutionValueParameterSet
executionParameter2.ObjectType = 50
executionParameter2.ParameterName = "LOGGING_LEVEL"
executionParameter2.ParameterValue = 3
executionParameters.Add(executionParameter2)
' Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
Dim executionParameter3 As New PackageInfo.ExecutionValueParameterSet
If (Trim(txtPreviousID.Text) <> "") Then
executionParameter3.ObjectType = 20
executionParameter3.ParameterName = "PreviousBatchID"
executionParameter3.ParameterValue = txtPreviousID.Text
executionParameters.Add(executionParameter3)
End If
' Get the identifier of the execution to get the log
Dim executionIdentifier As Long = ssisPackage.Execute(False, Nothing, executionParameters)
' Loop through the log and add the messages to the listbox
For Each message As OperationMessage In ssisServer.Catalogs("SSISDB").Executions(executionIdentifier).Messages
SSISMessagesListBox.Items.Add(message.MessageType.ToString() + ": " + message.Message)
Next
Catch ex As Exception
If ex.InnerException IsNot Nothing Then
SSISMessagesListBox.Items.Add(ex.Message.ToString() + " : " + ex.InnerException.Message.ToString())
Else
SSISMessagesListBox.Items.Add(ex.Message.ToString())
End If
End Try
End Sub
End Class
I'm starting to think that I did not understand environments correctly when it comes to SSIS. My environment was setup as TEST and PROD on their respective servers with the same variable names mapped to the same parameters but with different values. I am starting to believe I should have had the same Environment name on both the TEST and PROD server, which I would then refer too using my VB code. I have not been able to find out how to refer to the Environment using VB yet either though.
I would appreciate any help on the matter.
Cheers,
Johnathan
For the purpose ssis have given facility of configuration and you have to just create separate cofig file or db entry for your different environment .
https://msdn.microsoft.com/en-us/library/ms141682.aspx
You need to set the reference property of the package to be the ID of the environment.
To get the environment ID try:
DECLARE #environment_id AS BIGINT
SELECT #environment_id = reference_id FROM SSISDB.internal.environment_references where environment_name = 'your environment name'
To be able to use Environments inside a Visual Basic .NET program. You need to declare the Environment Reference and pass the reference to the Execute Method of the SSIS Package.
The following block of code is how it is done:
Dim re As EnvironmentReference
re = ssisServer.Catalogs("SSISDB").Folders("SSIS_PROJECTS").Projects("AgressoExport").References("AgressoExport", ".")
Dim executionIdentifier As Long = ssisPackage.Execute(False, re, executionParameters)
SSISDB is the catalog name, SSIS_PROJECTS is the folder name under the catalog that I am using. AgressoExport is my Project Name. ("AgressoExport", ".") refers to the Environment named AgressoExport under my project in the root of the Environment Folder.
Cheers

VB.NET - .accdb database not saving changes

I can't figure out why my code won't save to my .accdb database.
I am fetching data from a .accdb database file and displaying it in a DataGridView, and then allowing changes to be made to it there. (This is a stock control system.) After making changes, the user is meant to be able to send the data back so it is saved in the .accdb file.
I have looked online everywhere and tried multiple different ways of doing this. This is the way I am currently using to solve the problem, but when running the code it does not save to the .accdb file. (However, it throws up no errors.)
Public Class Database
Dim datatable As DataTable
Dim adapter As OleDb.OleDbDataAdapter
Dim dbCon As New OleDb.OleDbConnection
Dim dbProvider As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
Dim dbRsrc As String = "Data Source =" & System.IO.Directory.GetCurrentDirectory & "/Resources/List.accdb"
Dim binding As BindingSource
Dim cmdBuilder As OleDb.OleDbCommandBuilder
Private Sub Database_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
adapter = New OleDb.OleDbDataAdapter("Select * FROM List", dbCon)
datatable = New DataTable
adapter.FillSchema(datatable, SchemaType.Source)
adapter.Fill(datatable)
binding = New BindingSource
binding.DataSource = datatable
dbCon.Close()
StockTable.DataSource = binding
End Sub
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
'insert validation here
Try
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
cmdBuilder = New OleDb.OleDbCommandBuilder(adapter)
adapter.AcceptChangesDuringUpdate = True
adapter.Update(datatable)
dbCon.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString() & " Save Unsuccessful.")
End Try
End Sub
End Class
Not sure where I'm going wrong - when I hit the 'save' button, it should connect to the database, build a SQL query to update it and then update my datatable + .accdb database, right?
To test it, I've tried editing multiple columns and saving it, but when opening the file it still says the same values as it had before.
Any suggestions/pointers? I'm pretty newbie to VB.NET, learnt it about 3 months ago and only just starting to get fully into it.
Many thanks to the user "jmcilhinney" who helped me to reach this answer. I feel highly stupid at not realising that my code was working.
I used
Debug.WriteLine("Update value: " & adapter.Update(datatable))
Debug.WriteLine("Connection str: " & dbProvider & dbRsrc)
to find that my update command worked, and that in fact the output of my database file was in the /bin/ folder. I didn't realise that it used the /bin/ folder, and was looking in the root folder with the .VB files, etc.

Set SSIS database package path

I am trying to execute a SSIS package located in a database programatically.
I am using this API:
Imports Microsoft.SqlServer.Dts.Runtime
I have an image describing the path (in database) to package but I cannot figure out how to set the packagePath property properly in the LoadFromSqlServer method.
Here is the image describing my package path in database:
You will need to add a reference to Microsoft.SqlServer.Management.IntegrationServices. For me, it does not show up in the SQL Server folders and I could only find it in the GAC.
C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Management.IntegrationServices\11.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Management.IntegrationServices.dll
There's also a dependency from that assembly to
C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Management.Sdk.Sfc\11.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Management.Sdk.Sfc.dll
Sub Main()
'
' Do not fault me for my poor VB skills nor my lack of error handling
' This is bare bones code adapted from
' http://blogs.msdn.com/b/mattm/archive/2011/11/17/ssis-and-powershell-in-sql-server-2012.aspx
Dim folderName As String
Dim projectName As String
Dim serverName As String
Dim packageName As String
Dim connectionString As String
Dim use32BitRuntime As Boolean
Dim executionId As Integer
Dim integrationServices As Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices
Dim catalog As Microsoft.SqlServer.Management.IntegrationServices.Catalog
Dim catalogFolder As Microsoft.SqlServer.Management.IntegrationServices.CatalogFolder
Dim package As Microsoft.SqlServer.Management.IntegrationServices.PackageInfo
' Dimensions in your example
folderName = "SSISHackAndSlash"
' dimCalendar in your example
projectName = "SSISHackAndSlash2012"
serverName = "localhost\dev2012"
' dimCalendar in your example (no file extension)
packageName = "TokenTest.dtsx"
connectionString = String.Format("Data Source={0};Initial Catalog=msdb;Integrated Security=SSPI;", serverName)
integrationServices = New Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices(New System.Data.SqlClient.SqlConnection(connectionString))
' There is only one option for an SSIS catalog name as of this posting
catalog = integrationServices.Catalogs("SSISDB")
' Find the catalog folder. Dimensions in your example
catalogFolder = catalog.Folders(folderName)
' Find the package in the project folder
package = catalogFolder.Projects(projectName).Packages(packageName)
' Run the package. The second parameter is for environment variables
executionId = package.Execute(use32BitRuntime, Nothing)
End Sub
In addition to billinkc answer.
Here is the C# version of the code:
string folderName = "name";
string projectName = "name";
string serverName = "localhost";
string packageName = "name";
string connectionString = string.Format("Data Source={0};Initial Catalog=msdb;Integrated Security=SSPI;", serverName);
var integrationServices = new IntegrationServices(newSystem.Data.SqlClient.SqlConnection(connectionString));
var catalog = integrationServices.Catalogs["SSISDB"];
var catalogFolder = catalog.Folders[folderName];
var package = catalogFolder.Projects[projectName].Packages[packageName];
long execId = package.Execute(false, null);
In my case I had to add 4 dlls:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.IntegrationServices.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
All the dependencies can be found C:\Windows\assembly\GAC_MSIL\
If you want to find the package location deployed in SQL server.
Open SSMS.
Connect to Integration Services.
Go to View and Click "Object Explorer Details".
Now you select your package to know the package path in SQL server.
Take a look at the screenshot below.
Ignore the server name because it will be parameter for the LoadFromSqlServer method.
So package path should be : \Stored Package\MSDB\Data Collector\PerfCountersUpload.
Hope this helps.

Resources