adding connection string during installation of vb.net project - vb.net

I want to create an installer wherein the user specifies where the connection string of the database.
I've seen a articles like this but they're in C#.
like this one: http://www.codeproject.com/Tips/446121/Adding-connection-string-during-installation
I also tried to translate the code into vb.net but there are some errors I can't fix.
If anyone can tell me how to do it or any article that might help me is really a great help.
I want to do this in my vb.net project not in C#

Here is the code converted to VB .NET
'Installer.vb
Dim dataSource As String = "Data Source=" & Context.Parameters("DataSource")
Dim initialcatalog As String = "Initial Catalog=" & Context.Parameters("InitialCatalog")
Dim user As String = "User ID=" & Context.Parameters("UserID")
Dim password As String = "Password=" & Context.Parameters("Password")
dataSource = dataSource & ";" & initialcatalog & ";" & user & ";" & password
dataSource = dataSource
MessageBox.Show("instance=" & dataSource)
Dim map As New ExeConfigurationFileMap()
MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().Location & ".config")
'Getting the path location
Dim configFile As String = String.Concat(System.Reflection.Assembly.GetExecutingAssembly().Location, ".config")
map.ExeConfigFilename = configFile
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None)
Dim connectionsection As String = config.ConnectionStrings.ConnectionStrings("MyConnectionString").ConnectionString
Dim connectionstring As ConnectionStringSettings = Nothing
If connectionsection IsNot Nothing Then
config.ConnectionStrings.ConnectionStrings.Remove("MyConnectionString")
'MessageBox.Show("removing existing Connection String")
End If
connectionstring = New ConnectionStringSettings("MyConnectionString", dataSource)
config.ConnectionStrings.ConnectionStrings.Add(connectionstring)
config.Save(ConfigurationSaveMode.Modified, True)
ConfigurationManager.RefreshSection("connectionStrings")

Related

Kofax transformation - Update fields on form on validation

I use Kofax Transform to extract data from OCR.
For this i have a form with several inputs. Basically : name, surname, email.
My issue concerns the validation step.
I want to update the input fields on specific event (click on enter when the email field is selected and update the values from a database). On this database table I have 4 fields : id, name, surname and email
It's my first VBA expertience and I have to create a script:
Private Sub FillFormOneEmailValidated(ByVal pXDoc As CASCADELib.CscXDocument)
'define required properties
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim sqlRequest As String
Dim email As String
Dim dbHostServer As String
Dim dbUsername As String
Dim dbPassword As String
Dim dbName As String
Dim dbConnString As String
'Prapare the db connection
Set rs = New ADODB.Recordset : Set cn = New ADODB.Connection
dbHostServer = "127.0.0.1"
dbUsername = "root"
dbPassword = "root"
dbName = "dbtest"
'build the connection string and open connection to database
dbConnString = "Provider=MSDASQL;Driver={MySQL ODBC 5.3 Unicode Driver};
dbConnString = dbConnString & "Server=" & dbHostServer & ";"
dbConnString = dbConnString & "UID=" & dbUsername & ";"
dbConnString = dbConnString & "PWD=" & dbPassword & ";"
dbConnString = dbConnString & "database=" & dbName
'Create recordset and set conncetion
Set rs = New ADODB.Recordset : : Set cn = New ADODB.Connection
cn.ConnectionString = dbConnString
cn.Open
'build query
sqlRequest = "SELECT name, surname, email FROM users WHERE email = " & email
Set rs = cn.Execute(sqlRequest)
'iterate the values of the sql request
On Error Resume Next
rs.MoveFirst
pXDoc.Fields.ItemByName("name") = CStr(sqlRequest("name"))
rs.Close : Set rs = Nothing
cn.Close : Set cn = Nothing
End Sub
Here are my issues :
it seems that this code is not correct.
How can i "observe" an event on the email input (form) in KTA Transform ?
Avoid building sql query like that since its a potential injection risk. Look into using parameters. (Or hope nobody's kid is named bobby drop table, or be subject to a malicious user)
Also passwords in scripts are not recommended.
I'd look into the already built in functionalities of The database locator. And database dialog you can add to your validation mask.
If script is the only possible thing
You can use multiple events to to this. One way as you said is when the field is confirmed ValidationForm_AfterTableCellChanged.
You can see events available to you in the Project builder/Script editor by the dropdown options
enter image description here
Not sure for KTA, but in normal KT you can debug and observe other how methods are doing by enabling the Script debugging in the synchronization options.
The error in the script looks obvious
sqlRequest is your query as String variable. You must get your row data from the recordset. (i have not checked the rest of the script)

"Operation must be an updateable query" VB.Net OleDB for Excel

Ive been trying to find a solution for this problem without any success:
I'm using VB.NET and I need to read and update records from an Excel file. I use the OleDB API for that. It works fine for all the reading, but impossible to write to the file (Update or Insert queries)
Here is what I have:
My connection string:
Public connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\...\Resources\attempt.xls;Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"
Select query that works fine:
Dim checkQuery = "SELECT * FROM [Sheet1$] WHERE [TravellerPN] = #T"
Try
Using connection As New OleDb.OleDbConnection(Form.connString)
Dim checkCommand As New OleDbCommand(checkQuery, connection)
checkCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
connection.Open()
Dim reader As OleDbDataReader = checkCommand.ExecuteReader()
Dim path As String = ""
While reader.Read()
path = reader("Datapath").ToString
End While
reader.Close()
MsgBox(PN & " " & DP & " " & path,,)
If a record for the part number entered doesnt exist, and nothing is returned, insert a new line
If path = "" Then
Dim addQuery = "INSERT INTO [Sheet1$] ([TravellerPN],[Datapath]) VALUES (#T, #D)"
Dim addCommand As New OleDbCommand(addQuery, connection)
addCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
addCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
Dim rows As Integer = addCommand.ExecuteNonQuery()
And this was where it returns the error.
MsgBox(rows & " row added!",, "") 'Never diplayed
And other query that doesn't work either:
Else 'If does exist, confirm replacement'
Dim replaceResponse = MsgBox("A path already exists for " & PN & "." & vbNewLine & "Do you want to replace " & path & " with " & DP & "?", MsgBoxStyle.YesNo, "Overwrite previous datapath?")
Dim replaceQuery = "UPDATE [Sheet1$] SET [Datapath] = #D WHERE [TravellerPN]=#T"
Dim replaceCommand As New OleDbCommand(replaceQuery, connection)
replaceCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
replaceCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
Dim rows As Integer = replaceCommand.ExecuteNonQuery()
MsgBox(rows & " row updated!",, "")
End If
connection.Close()
End Using
I've tried to fix the issue: it could be caused by permissions, so I authorized even guests accounts to modify my folder.
If it were a ReadOnly mode in the connection: I tried adding Mode=ReadWrite but my connection String didn't work after that. (That option seems only available for ADO connections?)
I tried running the app as administrator
And finally, I'm posting this here hoping to get some help.
Sorry or the long post, I was trying to give all the elements that could potentially be a problem.
Thanks.

SQL Result to Global Variable

Within my MDIParent Me_Load I have an SQL query that returns user information based upon Windows ID. This works well, however I'd really like to move this logic out into perhaps a module and assign each value in the db to a global variable to be used elsewhere. I'd like to be able to access the contact_id in any child form of the parent MDI. I'm used to PHP where I'd just assign it to a session variable that I could reference anywhere.
This is my current SQL Code
Dim sql_query As String
Dim errorMessages As New StringBuilder()
Dim cnn = ConfigurationManager.ConnectionStrings("sql_connection_string").ConnectionString
Dim adapter As SqlDataAdapter
Dim ds As New DataTable()
Dim User_ID As String
Dim User_First_Name As String
Dim User_Last_Name As String
Dim User_Contact_CD As String
Dim User_Login As String
sql_query = "SELECT Contact_ID, First_Name_CH, Last_Name_CH, Contact_CD, Login_VC FROM [Worktool].[dbo].[vwEmployees_T] WHERE Login_VC = '" & username & "'"
Using connection As New SqlConnection(cnn)
Try
If connection.State = ConnectionState.Closed Then connection.Open()
adapter = New SqlDataAdapter(sql_query, connection)
adapter.Fill(ds)
User_ID = ds.Rows(0)("Contact_ID").ToString()
User_First_Name = ds.Rows(0)("First_Name_CH").ToString()
User_Last_Name = ds.Rows(0)("Last_Name_CH").ToString()
User_Contact_CD = ds.Rows(0)("Contact_CD").ToString()
User_Login = ds.Rows(0)("Login_VC").ToString()
connection.Close()
Catch ex As SqlException
MsgBox("Sorry, there was an issue with the connection. Please try again ! ")
Dim i As Integer
For i = 0 To ex.Errors.Count - 1
errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
MsgBox(errorMessages.ToString())
End Try
End Using
'Assign messages
main_window_welcome.Text = "Welcome back, " & Replace(User_First_Name, " ", "") & " " & Replace(User_Last_Name, " ", "")
variable username is
Public username = Environ$("Username")
You've declared the 4 variables in the class and they are private to that class. At this point your code works. Hilight those 4 variable declarations and Cut them. Your code shows errors because you just removed the declarations.
Add a module to your solution (name it what you want)
paste the declarations into the module body.
change the Dim to Public.
Your errors disappear.
Your variables are now public and available throughout your solution.

VB.NET Update to Excel

I am developing an application in Visual Basic using Visual Studio 2013. In this application I am attempting to use an oledb UPDATE to write data out to an Excel spreadsheet treated as a database. I have tried numerous different formats of this but I either get a syntax error or it pretends to work but nothing actually gets written to the file. Can anyone tell me what is wrong with this code:
Public Function WriteToExcel(ExcelPath As String, dtUser As DataTable)
Dim vOffice As String = dtUser.Rows(0).Item("Office").ToString
Dim vDivision As String = dtUser.Rows(0).Item("Division").ToString
Dim vSection As String = dtUser.Rows(0).Item("Section").ToString
Dim vUser As String = dtUser.Rows(0).Item("UserID").ToString
Dim ExcelconnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelPath & ";Extended Properties='Excel 12.0 Xml;HDR=YES';"
Dim BatchID As Long = 0
Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice WHERE [Primary User] = #uUser"
'Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice, " & _
'"Division = #uDivision, " & _
'"Section = #uSection " & _
'"WHERE [Primary User] = #uUser"
Using conn As New OleDb.OleDbConnection(ExcelconnString)
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#uOffice", vOffice)
cmd.Parameters.AddWithValue("#uDivision", vDivision)
cmd.Parameters.AddWithValue("#uSection", vSection)
cmd.Parameters.AddWithValue("#uUser", vUser)
Try
MessageBox.Show("Attempting to update " & vUser & ". " & vOffice & ", " & vDivision & ", " & vSection & "!")
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message & vbNewLine & ex.StackTrace)
End Try
End Using
End Function
Your SQL has two issues:
OleDbCommands use question marks ? as the placeholder for parameters, not #parameterName (that's for SqlCommands).
Section is a reserved keyword, so it needs to be escaped: [Section].

Connecting to Data Sources in the Script Task

I'm having some trouble using the connection manager from a script task in SSIS. The program will compile perfectly until I try using the connection that is set in the Environment.
Private Sub InsertLog(ByRef log() As String)
Dim conn As SqlClient.SqlConnection
conn = _
DirectCast(Dts.Connections("ConfigDB").AcquireConnection(Dts.Transaction), _
SqlClient.SqlConnection)
MsgBox(log(0) & " " & log(1) & " " & log(2) & " " & log(3) & Dts.Connections("ConfigDB").ConnectionString.ToString())
End Sub
If I comment out the Dim and DirectCast the package executes successfully and I can successfully get the connection string in a messagebox.
Data Source=PathToServer;Initial Catalog=DB;Provider=...;Integrated Security=...;Application Name=...;Auto Translate=False;
Has anyone else had this happen?
I have a solution. The reason why it failed was because of the Provider and Auto Translate, so my solution is to strip out what is not needed.
Dim strConnection As String = Dts.Connections("Automation").ConnectionString.ToString()
Dim regProvider As New Regex("Provider=([^;]*);")
Dim regTranslate As New Regex("Auto Translate=([^;]*);")
strConnection = regProvider.Replace(strConnection, "")
strConnection = regTranslate.Replace(strConnection, "")
Dim conn As New SqlClient.SqlConnection(strConnection)