Getting CommandLineArgs StartsWith Failing - vb.net

I've got an application. I haven't had to use command line arguments before but my research suggests my method isn't wrong. In VS2015, in my project properties->debug I've added /boxID=123 but when I debug, I get nothing in my inputVal variable. Where am I going wrong?
Imports Word = Microsoft.Office.Interop.Word 'needed for COM object interaction with MS Word
Imports System.Data.SqlClient 'needed for DB interactions
Imports System.IO 'needed for BLOB
Public Class Window
'set form level declarations
Dim appPath As String
Dim objWordApp As New Word.Application
Dim objDoc As Word.Document
Function boxIDfromCommandLine() As Integer
Dim inputArg As String = "/boxID="
Dim inputVal As String = ""
For Each s As String In My.Application.CommandLineArgs
If s.ToLower.StartsWith(inputArg) Then
inputVal = s.Remove(0, inputArg.Length)
End If
Next
If inputVal = "" Then
inputVal = "0"
End If
boxIDfromCommandLine = Convert.ToInt32(inputVal)
End Function
'form load subroutine
Private Sub Window_Load(ByVal sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Establish application path, replace appPath on deployment
Dim appPath As String = Application.StartupPath()
'Run application in foreground or background.
'If in background (false), be sure to add objDoc.close() and objWordApp.Quit()
objWordApp.Visible = False
'Declarations
Dim localDateTimeString As String = DateTime.Now.ToString
Dim localDateTimeFileName As String = DateTime.Now.ToString("yyyyMMddhhmm")
Dim soNumber As String = "No_SO_Selected"
Dim boxID As Integer = boxIDfromCommandLine()
Dim saveString As String 'file name format
Dim savePath As String = "C:\ITO_PackingLists" 'set folder location
Dim connection As SqlConnection = New SqlConnection() 'set SQL server connection string
...
...
...

Related

Blocking more folders and applications

As you can see here I block the directory called "cleo". If I have it in my folder I can't click connect. How can I check if, for example, "Cleo", "Images", "Logs" exist in browsed file. I don't think making multiple If statements would be good, is there any other way?
Private Sub connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connect.Click
Dim cleoPath As String
Dim filePath As String
filePath = System.IO.Path.Combine(TextBox2.Text, "gta_sa.exe")
cleoPath = System.IO.Path.Combine(TextBox2.Text, "cleo")
If File.Exists(filePath) Then
If Directory.Exists(cleoPath) Then
MsgBox("Pronasli smo cleo fajl u vasem GTA root folderu. Da se konektujete na server morate ga obrisati.")
Else
Dim p() As Process
p = Process.GetProcessesByName("samp")
If p.Count > 0 Then
MsgBox("Vec imate pokrenut SAMP - ugasite ga.")
Else
Try
Dim prozess As Process = Process.GetProcessesByName("samp")(0)
prozess.Kill()
Catch ex As Exception
End Try
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SAMP", "PlayerName", TextBox1.Text)
Process.Start("samp://193.192.58.55:7782")
Dim client As New TcpClient
client.Connect("193.192.58.55", 10924)
Dim sendbytes() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text)
Dim stream As NetworkStream = client.GetStream()
stream.Write(sendbytes, 0, sendbytes.Length)
End If
End If
Else
MsgBox("Da se konektujete morate locirati GTA San Andreas folder.")
End If
End Sub
End Class
You could use extension methods combined with a directoryinfo to check if any of a list of directory exists. Depending of if you just want a true/false return or if you need to process each directories (for instance, by adding a custom message with the name of the folders that prevent your application from continuing.
Public Module DirectoryInfoExt
<System.Runtime.CompilerServices.Extension()>
Public Function AnyExists(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As Boolean
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Any(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function GetExistingDirectories(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As IEnumerable(Of String)
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Where(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
End Module
An example the boolean return.
Dim BaseDirectory As String = "C:\Games\GTA"
Dim GamePath As New DirectoryInfo(BaseDirectory)
' Will not give the specific path that exists, only a Boolean if any of theses folder are found
Dim ModsFound As Boolean = GamePath.AnyExists("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
If Not ModsFound Then
'Connect
Else
' Do something
End If
An example using the list return to generate a custome message prompt stating the name of the specific folders found.
'This version gives a list instead.
Dim ModsFoundList As IEnumerable(Of String) = GamePath.GetExistingDirectories("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
Dim HasMod As Boolean = ModsFoundList.Count > 0
If HasMod Then
EvilModdedUserPrompt(ModsFoundList)
Exit Sub
End If
' Here, since HasMod is false, we can proceed with connection.
' Do connection
As for the EvilModdedUserPrompt method
Public Sub EvilModdedUserPrompt(ModsFoundList As List(Of String))
Dim OutputMessage As New Text.StringBuilder
OutputMessage.AppendLine("The following mods have been detected on your system:")
For Each Moditem As String In ModsFoundList
OutputMessage.AppendFormat("- {0}", Moditem)
OutputMessage.AppendLine()
Next
MessageBox.Show(OutputMessage.ToString)
End Sub

End of statement expected. - VB Code to WebService Error

I'm getting this error when trying to debug my VB code in Visual Studio to interact with a specific WebService .
Im not very familiar with Visual Basic.
The error is on the line Dim ticket_handle As String = " CR 1001 " ws.closeTicket ( Sid , " closed ticket " ticket_handle )
The complete code:
Imports System.IO Imports System.Xml
Imports System.Xml.Serialization
Imports WebReference
Partial Class _Default
Inherits System.Web.UI.Page
Dim ws As New USD_WebService
Dim sid As String
Dim userhandle, username, password As String
Dim attrVal(5), attr(0), prop(0) As String
Dim requestHandle, requestNumber As String
Dim persistent_id As String
Dim catAttrib(5) As String
Sub Main()
Dim ws As New USD_WebService
ws.Url = "http://hummer:8080/axis/services/USD_R11_WebService?wsdl"
Dim username, password
Dim sid
username = "servicedesk"
password = "password"
sid = ws.login(username, password)
Dim userhandle
userhandle = ws.getHandleForUserid(sid, username)
Dim USD As New WebReference.USD_WebService
sid = USD.login(username, password)
Dim ticket_handle As String = “cr:1001” ws.closeTicket(Sid,“ticket fechado”, ticket_handle)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ws.Url = "http://hummer:8080/axis/services/USD_R11_WebService?wsdl"
End Sub
End Class
Can anyone help me plis?!?!
In VB.NET, only one statement may be executed per line. Other languages, like Java or C# use a ';' to denote the end of a statement, however in VB.NET it is the end of a line. The compiler is trying to tell you that you have two statements on a single line and it expects there to only be one.
Dim ticket_handle As String = “cr:1001” ws.closeTicket(Sid,“ticket fechado”, ticket_handle)
Should be
Dim ticket_handle As String = “cr:1001”
ws.closeTicket(Sid,“ticket fechado”, ticket_handle)

Create Shortcut in StartUp folder (VB.NET)

I have this code and it's giving troubles:
Imports IWshRuntimeLibrary
Imports Shell32
Public Sub CreateShortcutInStartUp(ByVal Descrip As String)
Dim WshShell As WshShell = New WshShell()
Dim ShortcutPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(ShortcutPath &
Application.ProductName & ".lnk"), IWshShortcut)
Shortcut.TargetPath = Application.ExecutablePath
Shortcut.WorkingDirectory = Application.StartupPath
Shortcut.Descripcion = Descrip
Shortcut.Save()
End Sub
According to what I have read, this is how you create a shortcut in Startup. But, no matter how much I call this Sub, shortcut does not show up. I ALREADY look up to a lot of similar questions around S.O and various other sites.
I even tried to create the shortcut from other application and still doesn't show up as expected.
What am I missing?
You have two errors in your code:
1) The path isn't being concatenated properly so change this:
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(ShortcutPath & Application.ProductName & ".lnk"), IWshShortcut)
to this:
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(System.IO.Path.Combine(ShortcutPath, Application.ProductName) & ".lnk"), IWshShortcut)
2) You spelled Description wrong so change:
Shortcut.Descripcion = Descrip
to this:
Shortcut.Description = Descrip
Here is the fixed subroutine:
Public Sub CreateShortcutInStartUp(ByVal Descrip As String)
Dim WshShell As WshShell = New WshShell()
Dim ShortcutPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim Shortcut As IWshShortcut = CType(WshShell.CreateShortcut(System.IO.Path.Combine(ShortcutPath, Application.ProductName) & ".lnk"), IWshShortcut)
Shortcut.TargetPath = Application.ExecutablePath
Shortcut.WorkingDirectory = Application.StartupPath
Shortcut.Description = Descrip
Shortcut.Save()
End Sub
Imports Microsoft.Win32 and
Imports IWshRuntimeLibrary
TO CREATE A SHORTCUT
Private Sub btnCreateShortcut_Click_(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateShortcut.Click
'To create Start shortcut in the windows Startup folder:
Dim WshShell As WshShell = New WshShell
Dim SRT As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
'Fixing the Shortcut Location instead of StartupScreenLocker
'Name your Shortcut, Example \ScreenLocker.Ink
Dim ShortcutPath As String = SRT & "\ScreenLocker.lnk"
'Add shortcut.
Dim Shortcut As IWshRuntimeLibrary.IWshShortcut
Shortcut = CType(WshShell.CreateShortcut(ShortcutPath), IWshRuntimeLibrary.IWshShortcut)
Shortcut.TargetPath = Application.ExecutablePath
Shortcut.WorkingDirectory = Application.StartupPath
Shortcut.Save()
End Sub
TO DELETE THE SHORTCUT
Private Sub btnDeleteShortcut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteShortcut.Click
'To create Start shortcut in the windows Startup folder:
Dim Shortcut As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
'Name the Shortcut you want to delete, Example \ScreenLocker.Ink
Dim ShortcutPath As String = Shortcut & "\ScreenLocker.lnk"
'To delete the shortcut:
If IO.File.Exists(ShortcutPath) Then
IO.File.Delete(ShortcutPath)
End If
End Sub

Insert data into database by linking class to btnRegister

I am new for programming and trying to learn VB.net through youtube tutorials.
I created a windows form app for users to create new account.
I am also trying to apply the hash and salt technique to store the password for security reason.
The main issue I have is maintaining successful connection between a two class I called "DatabaseManager" and "DataHandling", codes in "btnRegister" and the database called "Test".
The program runs fine. When I click btnRegister after filling the "txtUsername.Text" and "txtPassword.Text", it gives me error that says "ColumnUser_IDdoes not allow nulls.".
So this is where I keep getting issues. I tried to make it work a lot and I have no idea why it is not recording the new data. Here are my codes. I use V Studio 2012. Please help.
Just to be clear I copied some of the codes from internet and tried to make them work with the class
Imports System
Imports System.IO
Imports System.Text
Imports System.Data.OleDb
Imports System.Data
Imports System.Windows.Forms
Imports System.Data.SqlClient
Imports System.Security.Cryptography
Public Class DatabaseManager
Private Const CONNECTION_STRING As String = "Data Source=(localdb)\Projects;Initial Catalog=Test;Integrated Security=True"
Private connection As SqlConnection = Nothing
Private usersdataadapter As SqlDataAdapter = Nothing
Sub New()
connection = New SqlConnection(CONNECTION_STRING)
usersdataadapter = New SqlDataAdapter("select * from Test", connection)
End Sub
Public Sub Register(ByVal Username As String, ByVal Password As String)
connection.Open()
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
Dim newRecord As DataRow = table.NewRow()
newRecord("Username") = Username
newRecord("Password") = Password
table.Rows.Add(newRecord)
Dim command As New SqlCommandBuilder(usersdataadapter)
usersdataadapter.Update(usersDataset, "Test")
usersDataset.Dispose()
connection.Close()
End Sub
Public Function UsernameAvailable(ByVal username As String) As Boolean
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
usersdataadapter.Fill(usersDataset, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
For i As Integer = 0 To table.Rows.Count - 1
Dim currnetUser As String = table.Rows(i)("Username").ToString().Trim()
If (currnetUser = username) Then
usersDataset.Dispose()
connection.Close()
Return False
End If
Next
Return True
usersDataset.Dispose()
connection.Close()
End Function
Public Function Login(ByVal username As String, ByVal password As String) As Boolean
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
usersdataadapter.Fill(usersDataset, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
For i As Integer = 0 To table.Rows.Count - 1
Dim currnetUser As String = table.Rows(i)("Username").ToString().Trim()
Dim currnetPassword As String = table.Rows(i)("Password").ToString().Trim()
If (currnetUser = username AndAlso currnetPassword = password) Then
usersDataset.Dispose()
connection.Close()
Return True
End If
Next
usersDataset.Dispose()
connection.Close()
Return False
End Function
End Class
Imports System
Imports System.Text
Imports System.Data.OleDb
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Security.Cryptography
Public Class DataHandling
Inherits Form1
Public Shared Function GenerateRandomString() As String
Dim i_key As Integer
Dim Random1 As Single
Dim arrIndex As Int16
Dim sb As New StringBuilder
Dim RandomLetter As String
Dim KeyLetters As String = "abcdefghijklmnopqrstuvwxyz"
Dim KeyNumbers As String = "0123456789"
Dim KeyLength As Integer = 12
Dim LettersArray = KeyLetters.ToCharArray
Dim NumbersArray = KeyNumbers.ToCharArray
For i_key = 1 To KeyLength
Randomize()
Random1 = Rnd()
arrIndex = -1
If (CType(Random1 * 111, Integer)) Mod 2 = 0 Then
Do While arrIndex < 0
arrIndex = _
Convert.ToInt16(LettersArray.GetUpperBound(0) _
* Random1)
Loop
RandomLetter = LettersArray(arrIndex)
If (CType(arrIndex * Random1 * 99, Integer)) Mod 2 <> 0 Then
RandomLetter = LettersArray(arrIndex).ToString
RandomLetter = RandomLetter.ToUpper
End If
sb.Append(RandomLetter)
Else
Do While arrIndex < 0
arrIndex = _
Convert.ToInt16(NumbersArray.GetUpperBound(0) _
* Random1)
Loop
sb.Append(NumbersArray(arrIndex))
End If
Next
Return sb.ToString
End Function
Public Shared Function CheckPassword(ByVal plainText As String, ByVal passwordHash As Byte(), ByVal salt As Byte()) As Boolean
Dim encoding As New System.Text.UTF8Encoding
'Retrieve Salt String from byte array
Dim saltStr As String = encoding.GetString(salt)
Dim hashable As String = Trim(plainText) & Trim(saltStr)
' Convert into hash strings
Dim testhash As String = EncryptStringAsHash(hashable)
Dim realHash As String = encoding.GetString(passwordHash)
' Compare and return result
Return testhash = realHash
End Function
Public Shared Function EncryptStringAsHash(ByVal value As String) As String
Dim encoding As New System.Text.UTF8Encoding
Dim stringBytes As Byte() = encoding.GetBytes(value)
Dim SHhash As SHA512Managed = New SHA512Managed
Dim hash As String = Convert.ToBase64String(SHhash.ComputeHash(stringBytes))
Return hash
End Function
Public Shared Function ConvertStringToByteArray(ByVal value As String) As Byte()
Dim encoding As New System.Text.UTF8Encoding
Return encoding.GetBytes(value)
End Function
End Class
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Data.OleDb
Imports System.Windows.Forms
Imports System.Data.OleDb.OleDbConnection
Imports System.Data.SqlClient
Public Class Form1
Dim maxrows As Integer
Dim incdec As Integer
Dim con As New OleDb.OleDbConnection
Dim dbprovider As String
Dim dbsource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
Dim dbprovider As String
Dim dbsource As String
dbprovider = "PROVIDER = Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source=(localdb)\Projects;Initial Catalog=Test;Integrated Security=True"
con.ConnectionString = dbprovider & dbsource
End Sub
Private Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
Dim dbmanager As New DatabaseManager
Dim Data As New DataHandling
'Generate Hash and Salt for password
Dim salt As String = DataHandling.GenerateRandomString
Dim hashable As String = Trim(txtPassword.Text) & Trim(salt) 'txtPassword.Text used to be password
Dim hash As String = DataHandling.EncryptStringAsHash(hashable)
Dim confirmationId As String = System.Guid.NewGuid.ToString
Dim reg As user
reg.Username = txtUsername.Text 'txtUsername.Text used to be username
reg.Password = DataHandling.ConvertStringToByteArray(hash)
reg.Salt = DataHandling.ConvertStringToByteArray(salt)
If dbmanager.UsernameAvailable(txtUsername.Text) Then
dbmanager.Register(txtUsername.Text, txtPassword.Text)
Dim password As String
If txtPassword.Text = String.Empty Then
password = "217tABCDEF42#$tolq"
Else
password = txtPassword.Text
End If
Dim salt As String = GenerateRandomString(12)
Dim hashable As String = Trim(password) & Trim(salt)
MsgBox("Hashable = " & hashable)
Dim hash As String = EncryptStringAsHash(hashable)
CheckPassword(password, ConvertStringToByteArray(hash), ConvertStringToByteArray(salt))
frmAccessGranted.Show()
Me.Hide()
Else
MessageBox.Show("Cannot Register, Username Already Taken!")
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtUsername.Clear()
txtPassword.Clear()
End Sub
End Class
I think your User table User_id value is just missing Identity Specification option. It makes the User_id field to be generated automatically and increased by 1 (by default) for each User you add into
If you have SQL Server management studio you can put this option on:
Right click User table -> Select "Desing" -> Select "User_id" field -> in "Column Propetries" window put "Indentity Specification" option to "Yes" and save
Example SQL Command to create table could be something like this:
CREATE TABLE User (User_id BIGINT IDENTITY NOT NULL, Username NVARCHAR(100) NOT NULL, Password NVARCHAR(100) NOT NULL)
The problem in your code is not in the VB side, it is in the database.
You have set primary key to UserId but you are not passing any values to the userId, you are just passing values to the user name and password.
So there are two ways to solve this issues
you can send userid also from the VB code
you can just make the column UserId as autoincrement field by the following code
CREATE TABLE [dbo].[Test1](
[id] [int] IDENTITY(1,1) NOT NULL,
YourColumnname1 datatype,
YourColumnname2 datatype
)
This works only in the later versions of sqlserver 2008
alter table tablename
alter column columnname
add Identity(100,1)
To know more Click here

Add Multiple extensions to string VB.net

I have the below code that looks for the value displayed in a combobox then populates a listbox with the selected file names that relate the extension selected (maybe the code will make more sense!)
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim lyxfle As New IO.DirectoryInfo(sPath)
Dim diar1 As IO.FileInfo() = lyxfle.GetFiles()
Dim MyExt As String = Nothing
Dim MyVariable As String
Dim sFile As String
MyVariable = ComboBox1.Text
If MyVariable = "Forms" Then MyExt = "*.pff"
If MyVariable = "Reports" Then MyExt = "*.mdb"
If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm"
ListBox2.Items.Clear()
sFile = Dir$(sPath & MyExt)
Do While CBool(Len(sFile))
ListBox2.Items.Add(System.IO.Path.GetFileNameWithoutExtension(sFile))
sFile = Dir$()
Loop
End Sub
The following line is what i'm struggling with
If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm"
I basically need it to also look at the extensions .xls & .xlsx and include all files within the list
Both Path and sPath are declared as Private Strings at the top of the class
Any advice
I'll try to keep this simple and use what you have then. This code will get all the files from the folder. Then it will match it to your MyExt selection. As you can see I have added the excel file extensions with a comma between them (can be any special character really). Then all I have to do is see if MyExt contains the FileExtension and add it to the listbox:
Dim MyExt As String = Nothing
Dim MyVariable As String
Dim sFile As String
MyVariable = ComboBox1.Text
If MyVariable = "Forms" Then MyExt = "*.pff"
If MyVariable = "Reports" Then MyExt = "*.mdb"
If MyVariable = "Spreadsheets" Then MyExt = ".xlsm,.xls"
Dim lyxfle As New IO.DirectoryInfo(sPath)
Dim diar1 As IO.FileInfo() = lyxfle.GetFiles()
For Each file As IO.FileInfo In diar1
If MyExt.Contains(file.Extension) Then
ListBox2.Items.Add(IO.Path.GetFileNameWithoutExtension(file.Name))
End If
Next