Write a visual basic script in a vb.net application. - vb.net

In my application I have created I need it to write a visual basic script to change the ip address
The script is as follows...
Dim strIPAddress
Dim strSubnetMask
Dim strGateway
Dim intGatewayMetric
Dim strDns1
Dim strDns2
strIPAddress = "192.168.1.211"
strSubnetMask = "255.255.255.0"
strGateway = "192.168.0.11"
intGatewayMetric = 1
strDns1 = "8.8.8.8"
strDns2 = "4.4.4.4"
Set objShell = WScript.CreateObject("Wscript.Shell")
objShell.Run "netsh interface ip set address name=""Local Area Connection"" static " & strIPAddress & " " & strSubnetMask & " " & strGateway & " " & intGatewayMetric, 0, True
objShell.Run "netsh interface ip set dns name=""Local Area Connection"" static "& strDns1, 0, True
objShell.Run "netsh interface ip add dns name=""Local Area Connection"" addr="& strDns2, 0, True
Set objShell = Nothing
WScript.Quit
The way I am trying to write this is like the following..
Directory.CreateDirectory("C:\SpecMee\IPChanger\")
Dim objwriter As New System.IO.StreamWriter("C:\SpecMee\IPChanger\IpChanger.vbs")
objwriter.WriteLine("Dim strIPAddress" & Environment.NewLine & "Dim strSubnetMask" & Environment.NewLine & "Dim strGateWay" & Environment.NewLine & "Dim intGatewayMetric" & Environment.NewLine & "Dim strDns1" & Environment.NewLine & "Dim strDns2" & Environment.NewLine & "strIPAddress = """ & Environment.NewLine & TB_IPAddress & Environment.NewLine &)
objwriter.Close()
MessageBox.Show("Created")
The problem I am having is one, it is taking ages and two, how would i include the "" in the script.
I dont mind spending time on this, I just dont know if im going about this the right way.
any help would be appreciated.
Thanks
Chris

Add the script as a text file resource to your project. Replace all instances of the IP Address in the script with some known value, then use string.replace:
Const ipPlaceHolder As String = "##IP##"
Dim scriptContent As String = My.Resources.script.Replace(ipPlaceHolder, myTextBox.Text)
IO.File.WriteAllText("C:\SpecMee\IPChanger\IpChanger.vbs", scriptContent)
Where myTextBox contains user input and the text file resource is named "Script"

Two quotation marks in a row makes one in the output.
"And he said ""Thar she blows!"""
( You have two questions in one. That is not considered good customs on Stackoverflow. )

Related

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].

Insert SQL Query not executed

I am doing the programming on my computer and it works fine-the program, the database itself, inserting to the database is also working fine. But when I publish it and install the program on another computer. It crashes and does not execute the INSERT command.
Here is my code.
Private Sub cmdBlank_Click(sender As System.Object, e As System.EventArgs) Handles cmdBlank.Click
strTariff1 = txtPart1.Text & " " & txtPName1.Text & " " & txtQty1.Text & " " & txtU1.Text
strTariff2 = txtPart2.Text & " " & txtPName2.Text & " " & txtQty2.Text & " " & txtU2.Text
strTariff3 = txtPart3.Text & " " & txtPName3.Text & " " & txtQty3.Text & " " & txtU3.Text
strTariff4 = txtPart4.Text & " " & txtPName4.Text & " " & txtQty4.Text & " " & txtU4.Text
'strTariff5 = txtPart5.Text & " " & txtPName5.Text & " " & txtQty5.Text & " " & txtU5.Text
Call saveToDb()
frmreportax.Show()
End Sub
Private Function saveToDb()
conn.Close()
Dim cmdAdd, cmdCount, cmdAdd2 As New iDB2Command
Dim sqlAdd, sqlCount, sqlAdd2 As String
Dim curr1, curr2, curr3, curr4 As String
Dim count As Integer
conn.ConnectionString = str
conn.Open()
'Check for duplicate entry
sqlCount = "SELECT COUNT(*) AS count FROM cewe WHERE transport=#transport AND blnum=#blnum"
With cmdCount
.CommandText = sqlCount
.Connection = conn
.Parameters.AddWithValue("#transport", frmPart1.txtTransport.Text)
.Parameters.AddWithValue("#blnum", frmPart1.txtNo.Text)
End With
count = Convert.ToInt32(cmdCount.ExecuteScalar())
If count <> 0 Then
MsgBox("Duplicate Entry: " & frmPart1.txtTransport.Text, vbOKOnly + vbExclamation)
Else
sqlAdd = "INSERT INTO cewe (page) " & _
"VALUES (#page) "
With cmdAdd
.Parameters.AddWithValue("#page", Val(frmPart1.txtPage.Text))
.CommandText = sqlAdd
.Connection = conn
.ExecuteNonQuery()
End With
end if
cmdAdd.Dispose()
cmdAdd2.Dispose()
conn.Close()
end function
Please tell me what I am doing wrong? When I run and install the program on my PC, it works perfectly fine. But when I run/install it on another PC, it crashes after the cmdBlank is clicked.
There could be a number of things causing the issue but the first place to look is any error logs or crash report that may give some indication of the problem. Try debugging or logging to get a better picture. Beyond that there are some small suggestions that may help below.
Does the other computer have access to the database you are pointing to? Is the database connection pointing to localhost? In which case you will want to ensure that you have the same credentials (host, username, password, port etc.) set up on the database server on new computer. Are database drivers installed on new computer? What are the fundamental differences between the two machines?
AS400 iSeries DB2 needs to be updated to version 6.xx.0800 and did the tweak!
Installer can be found here
http://www-03.ibm.com/systems/power/software/i/access/windows_sp.html
Problem solved!

Using the process object with multiple arguments

I have a piece of code that calls MSTEST with multiple arguments defining a specific set of tests to run and an environment to run it in. Currently the code looks like this (a bit messy but it works):
Process.Start(Environment.GetEnvironmentVariable("VS110COMNTOOLS")
& "..\Ide\MSTEST.EXE", "/Testsettings:""" & rwSettings & """"
& " /Testcontainer:""" & rwContainer & """" & " /Resultsfile:"""
& rwResults & """")
With the various variables defined previously. I had to use the GetEnvironmentVariable("VS110COMNTOOLS") call because I can't guarantee an install location for Visual Studio and need access to the MSTEST executable. "..\Ide\MSTEST.EXE" is because the environment variable will only get me to the right area and I'll need to have the system navigate to IDE before it finds MSTEST.
I want to clean this up because it's not very elegant or readable, and also because I want to be able to raise events running this process. However, I'm not seeing documentation on how the Process class handles arguments. How can I have the Process object I create handle the multiple arguments (that might have spaces in the name)?
You may try this:
Dim Testsettings As String = "/Testsettings:"""
Dim Testcontainer As String = " /Testcontainer:"""
Dim Resultsfile As String = " /Resultsfile:"""
Dim Quote As String = """"
Dim p As New Process()
p.StartInfo.FileName = Environment.GetEnvironmentVariable("VS110COMNTOOLS")
& "..\Ide\MSTEST.EXE"
p.StartInfo.Arguments = Testsettings & rwSettings & Quote & Testcontainer
& rwContainer & Quote & Resultsfile & rwResults & Quote
p.Start()

Arguments from Visual Basic to Batch File

I know this is easy. I am an administrator, not a FT programmer. I am trying to pass the prjFilename and emailFilename arguments to a Batch file. To ensure the values are correct, I am popping a MsgBox in the Else branch. Everything is fine there. The problem is that when I attempt to use the variable in the Batch file, that variable string is cut off at the very first space in the filename path.
So when I echo %1% to test it, I get a truncated path. Any help is appreciated.
If prjFilename = "" Then
MsgBox("Please select a GSA Project File to process")
ElseIf emailFilename = "" Then
MsgBox("Please select a list of emails to process")
Else
Dim DosRun As Process = New Process
Dim strArgs As String
MsgBox(prjFilename)
MsgBox(emailFilename)
strArgs = prjFilename & " " & emailFilename
MsgBox(strArgs)
DosRun.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
DosRun.StartInfo.FileName = "C:\Users\Eric\Desktop\KRUSH\krush.cmd"
DosRun.StartInfo.Arguments = prjFilename & " " & emailFilename
DosRun.Start()
If either of prjFilename or emailFilename contain spaces, then you need to place double quotation characters around them when passing them to the batch file. A double quotation character literal in VBA is """" (I kid you not).
strArgs = """" & prjFilename & """" & " " & """" & emailFilename & """"
I normally define Public Const vbQuote as String = """" at the top of a module and use that.