I would like to create a console program in VB.net that would allow parameters. What i would like to do is in the code below add parameters so the webpart page can be created from the Run menu. e.g. C:.......\MyProgram.exe "Design" --This would then create the Design webpart page.
I tried looking at the internet but was not very successfull. any help would be greatly appreciated.
Module Main
Public Sub Main(ByVal args As String())
Dim prj As String
Dim site As New SPSite("http://site/")
Dim web As SPWeb = site.AllWebs(0)
Dim list As SPList = web.Lists("ListName")
Dim postInformation As String = "<?xml version=""1.0"" encoding=""UTF-8""?><Method><SetList Scope=""Request"">" + list.ID.ToString + "</SetList><SetVar
Name=""ID"">New</SetVar><SetVar Name=""Cmd"">NewWebPage</SetVar><SetVar
Name=""Type"">WebPartPage</SetVar><SetVar Name=""WebPartPageTemplate"">2</SetVar><SetVar
Name=""Title"">" + prj.ToString + "</SetVar><SetVar
Name=""Overwrite"">true</SetVar></Method>"
Dim processBatch As String = web.ProcessBatchData(postInformation)
'Display the results...
Console.WriteLine(processBatch)
Console.WriteLine("New Web part page added successfully")
Console.ReadLine()
End Sub
End Module
Thanks in advance!
Public Sub Main(ByVal sArgs() As String)
If sArgs.Length = 0 Then 'If there are no arguments
Console.WriteLine("Hello World! <-no arguments passed->") 'Just output Hello World
Else 'We have some arguments
Dim i As Integer = 0
While i < sArgs.Length 'So with each argument
Console.WriteLine("Hello " & sArgs(i) & "!") 'Print out each item
i = i + 1 'Increment to the next argument
End While
End If
End Sub
Hope this helps, for accessing the command line arguments.
Great answer by: Rajesh Sitaraman
Related
I have been trying to figure out a way to make it so everytime i launch my application it renames the application to a random string.
My application is in VB.NET
This is my frmLogin.vb (i put the code inside same class as login, since login is my start window, didnt know where else to put it)
Code:
Private Shared Sub Main(ByVal args As String())
Const REGISTRY_KEY As String = "HKEY_CURRENT_USER\Prototype"
Const REGISTY_FIRSTRUN As String = "FirstRun"
Const REGISTY_LASTNAME As String = "LastName"
Dim RandomTitle As String = RandomString(RandomShit.[Next](5, 15)) & ".exe"
Try
If Convert.ToInt32(Microsoft.Win32.Registry.GetValue(REGISTRY_KEY, REGISTY_FIRSTRUN, 0)) = 0 Then
Console.Title = RandomTitle
Dim TempPath As String = Convert.ToString(Microsoft.Win32.Registry.GetValue(REGISTRY_KEY, REGISTY_LASTNAME, 0))
If AppDomain.CurrentDomain.FriendlyName <> "RandomShit.exe" Then
File.Delete("RandomShit.exe")
End If
If File.Exists(TempPath) Then
File.Delete(TempPath)
End If
Microsoft.Win32.Registry.SetValue(REGISTRY_KEY, REGISTY_FIRSTRUN, 1, Microsoft.Win32.RegistryValueKind.DWord)
Microsoft.Win32.Registry.SetValue(REGISTRY_KEY, REGISTY_LASTNAME, Directory.GetCurrentDirectory() & "\" + AppDomain.CurrentDomain.FriendlyName, Microsoft.Win32.RegistryValueKind.String)
End If
Finally
End Try
End Sub
I am not sure whether below code completely satisfied your requirement. I hope below works for you to rename an executable file:
File.Move(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "randomstring.exe"))
Is it possible to return the arguments from the processPath in this example?
This might make more sense, sorry.
Dim processName As String
Dim processPath As String
If processName = "cmd" Then
Dim arguments As String() = Environment.GetCommandLineArgs()
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments))
End If
A simple (and clean) way to accomplish this would be to just modify your Sub Main as follows,
Sub Main(args As String())
' CMD Arguments are contained in the args variable
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", args))
End Sub
The VB.Net solution to your problem is to use Command() VB.Net function when you search to display command's line of currently executed process.
Sub Main(args As String())
Dim sCmdLine As String = Environment.CommandLine()
Console.WriteLine("CommandLine: " & sCmdLine)
Dim iPos = sCmdLine.IndexOf("""", 2)
Dim sCmdLineArgs = sCmdLine.Substring(iPos + 1).Trim()
Console.WriteLine("CommandLine.Arguments: " & sCmdLineArgs)
End Sub
The first outpout will display the complete command's line with name of program.
The second output will display only the command's line without program's name.
Using args is C/C++/C#/Java technic.
Using CommandLine() function is pure VB and is more intuitive because is return command's line as typed by user without supposing that arguments are type without blank.
Example:
LIST-LINE 1-12, WHERE=(20-24='TYPES'),to-area=4
LIST-LINE 1 - 12, WHERE = ( 20-24 = 'TYPES' ) , to-area = 4
In this command's syntax, arguments are separated by COMMA and not by spaces.
In this case, it is better to not use args technic that is more linked to C and Unix where command syntax accepts arguments separated by space !
Another option
Sub WhatEver()
Dim strArg() as string
strArg = Command().Split(" ")
' strArg(0) is first argument and so on
'
'
End Sub
Here is my code.
Yes, I am using both, DropNet and Dropbox APIs as I found the DropNet upload works nicely. But I am trying to use the Dropbox one to check for filename (as I couldn't get it to work on DropNet and could not find any help about it online)
I have little doubt that my problem has something to do with the whole Async & Await , as I have never worked with this stuff before.
The File Upload & Get Share both work just fine.
This is a VB.Net Website.
When I run it, it freezes in side the DoesDropBoxFileExist function
Imports Dropbox.Api
Imports DropNet
Imports DropNet.Models
Partial Class _Default
Inherits System.Web.UI.Page
Dim br As String = "<br>"
Public FileName As String
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FileUpload1.HasFile Then
Dim dropNet_client As New DropNetClient("", "", "")
Dim dropBox_client As New DropboxClient("")
FileName = FileUpload1.PostedFile.FileName
Response.Write("before: " & FileName & br)
MsgBox(1)
FileName = DoesDropBoxFileExist(dropBox_client).Result
MsgBox(3)
Response.Write("after: " & FileName & br)
Dim content As Byte() = FileUpload1.FileBytes
Dim pathToFile As String = Server.MapPath("~")
'Response.Write(pathToFile)
dropNet_client.UploadFile("/AlertImages/", FileName, content, True)
Dim shareResponse As ShareResponse = dropNet_client.GetShare("/AlertImages/" & FileName)
Response.Write(shareResponse.Url)
If Not FileName.ToLower.Contains("pdf") Then
Dim rawBytes As Byte() = dropNet_client.GetThumbnail("/AlertImages/" & FileName, 2)
Dim base64String As String = Convert.ToBase64String(rawBytes, 0, rawBytes.Length)
Image1.ImageUrl = "data:image/png;base64," & base64String
Image1.Visible = True
End If
dropBox_client.Dispose()
End If
End Sub
Private Async Function DoesDropBoxFileExist(_client As DropboxClient) As Threading.Tasks.Task(Of String)
Dim rtn As String = FileName
Dim list = Await _client.Files.ListFolderAsync("/AlertImages")
MsgBox(2)
' show folders then files
For Each item As Files.Metadata In list.Entries.Where(Function(i) i.IsFolder)
If item.Name = FileName Then
FileName = FileName & Now.ToString
End If
Response.Write(" < b > " & item.Name & "</b>" & br)
'Dim list2 As ListFolderResult = Await dbx.Files.ListFolderAsync(item.Name)
'For Each itm As Files.Metadata In list2.Entries.Where(Function(j) j.IsFile)
' Response.Write(item.Name & " : " & item.AsFile.Size & br)
'Next
Next
For Each item As Files.Metadata In list.Entries.Where(Function(i) i.IsFile)
Response.Write("'" & item.Name & "' '" & FileName & "'" & br)
If item.Name = FileName Then
Response.Write("test" & br)
rtn = FileName & "_" & Now.ToString
End If
Next
Return rtn
End Function
End Class
METHOD 1
To check in VB.NET if a file exists in Dropbox using the API, you can use this method.
First we create a button with a click event as follows:
Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
'FileToCheck is declared in Form1 as Public Shared
'FileFound is declared in Form1 as Public Shared
FileToCheck = cmbFiles.Text
FileFound = False
Dim task1 = Task.Run(Function() CheckFileMetadata())
task1.Wait()
If FileFound = True Then
'Do something
Else
'Do something else
End If
End Sub
And now the function:
Private Async Function CheckFileMetadata() As Task
Using dbx = New DropboxClient(DbxToken) 'DbxToken = your token text
Try
Await dbx.Files.GetMetadataAsync(Form1.FileToCheck)
FileFound = True
Debug.WriteLine("Found it!")
Catch exapi As ApiException(Of Dropbox.Api.Files.GetMetadataError)
If exapi.ErrorResponse.IsPath And exapi.ErrorResponse.AsPath.Value.IsNotFound Then
Debug.WriteLine("Nothing found at " + Form1.FileToCheck)
End If
Catch ex As Exception
Debug.WriteLine("Error checking file metadata" + vbCrLf + ex.ToString)
End Try
End Using
End Function
This method was adapted from the code here.
METHOD 2
This example demonstrates using VB.NET to recursively iterate through all Dropbox folders to retrieve the names of all files and put them into a collection. Then we check to see if our file is in the collection or not. This method does work, but it's not as efficient as the method above for obvious reasons. I've left it here because it illustrates some additional methods that might help someone.
A couple of notes:
If you have a lot of files and/or folders, there can be a delay due to all of the calls that have to be made to do the recursive processing.
DbxFolders and DbxFiles are declared as Public in the main form class, like so:
Public DbxFolders As New List(Of String)
Public DbxFiles As New List(Of String)
Note use of the .tolower since the Dropbox API returns all found paths in all lowers:
Private Sub btnWalk_Click(sender As Object, e As EventArgs) Handles btnWalk.Click
DbxFolders.Clear()
DbxFiles.Clear()
Dim FindIt As String = "/Folder/File-To-Find.txt".ToLower
Dim task2 = Task.Run(Function() GetTree(String.Empty))
task2.Wait()
If DBFileExists(FindIt) Then MsgBox("Found it!") Else MsgBox("File not found")
End Sub
Private Async Function GetTree(dir As String) As Task
Using dbx = New DropboxClient("Your_Token_Goes_Here")
Dim list = Await dbx.Files.ListFolderAsync(dir)
For Each item In list.Entries.Where(Function(i) i.IsFile)
DbxFiles.Add(item.PathLower)
Next
For Each item In list.Entries.Where(Function(i) i.IsFolder)
DbxFolders.Add(item.PathLower)
Await GetTree(item.PathLower)
Next
End Using
End Function
Private Function DBFileExists(file As String) As Boolean
If DbxFiles.IndexOf(file) > -1 Then Return True Else Return False
End Function
DISCUSSION
Method 1 is obviously the more efficient of the two methods by far because we only call the API once. Note how the ApiException is used in Try-Catch to determine that the file was not found.
Method 2 illustrates some additional concepts that were helpful to me to learn, so I've left it here because someone may have a scenario where this code and the lists that it creates comes in handy.
Note that when we call GetTree(String.Empty), it would be more efficient to pass the specific folder to look in, instead of starting at the root, since we are attempting to match the full path (/path/to/file.txt) in this example anyway, but I wanted to illustrate the recursive iteration because it might be needed in a different situation.
If you don't care what folder an item is in, but only want to see if it exists in a folder without regard to which folder that is, then you would need to use this recursive iteration but instead of item.pathlower you would want to collect item.name instead.
If desired, you can process the collected file list from Method 2 with a simple loop:
For each DbxFile as string in DbxFiles
'Do something
Next
There's lots and lots of pages on the internet regarding threading but I can't seem to get my head around it.
I have a Form, which on the click of a button, loops through a file and reads it line by line. Each line is the login details for different FTP sites.
When it reads a line, it Dim's a variable as a new instance of a class named CallFTP using the login details.
It then Dim's a variable as a new Thread using a function in CallFTP named PerformFTP.
PerformFTP returns a string with the results of the FTP and I want to add this to a ListBox on the form that began it all.
The code for the button goes like this...
Private Sub cmdRun_Click(sender As Object, e As EventArgs) Handles cmdRun.Click
For Each _FTPLine As String In Split(_FTPDetails, vbNewLine)
Dim _Active As Boolean = CBool(Split(_FTPLine, "|")(7))
If _Active Then
_CurNum += 1
_ID = Format(Now.Year, "0000") & Format(Now.Month, "00") & Format(Now.Day, "00") & Format(Now.Hour, "00") & Format(Now.Minute, "00") & Format(Now.Second, "00") & Format(Now.Millisecond, "000") & Format(_CurNum, "00000")
Dim _FTP As New CallFTP(_ID, Split(_FTPLine, "|")(0), Split(_FTPLine, "|")(1), Split(_FTPLine, "|")(2), Split(_FTPLine, "|")(3), Split(_FTPLine, "|")(4), Split(_FTPLine, "|")(5), Split(_FTPLine, "|")(6))
Dim _Thread = New Thread(New ThreadStart(AddressOf _FTP.PerformFTP))
With _Thread
.IsBackground = True
.Start()
End With
End If
Next _FTPLine
End Sub
The class is as below (not quite but you don't need the rest of the code lol)
Public Class CallFTP
Private _ID As String = ""
Private _Response As String = ""
Private _IPAddress As String = ""
Private _Port As String = ""
Private _User As String = ""
Private _Pass As String = ""
Private _Remote As String = ""
Private _Local As String = ""
Private _InOut As String = ""
Public Sub New(ID As String, Server As String, PortNum As String, Username As String, Password As String, RemoteDir As String, LocalDir As String, InOrOut As String)
_ID = ID
_IPAddress = Server
_Port = PortNum
_User = Username
_Pass = Password
_Remote = RemoteDir
_Local = LocalDir
_InOut = InOrOut
End Sub
Public Function PerformFTP() As String
Return "This is a test"
End Function
End Class
Could anyone explain how I would call a sub named LogMessage on a module named modMisc (which adds a string to a ListBox on the main form)?
I've read that you need to invoke it but everything I read seems to give me a headache and make me need to lie down in a dark room for a few hours.
Is anyone capable of explaining as though you're speaking to a 2 year old? :)
Any help would be much appreciated.
You need to invoke a delegate to update your GUI if you're going to update it from another thread that from where it was created.
1º Your delegate must match (have the same signature) than the method you'll use:
Delegate Sub LogMessageExampleDelegate(ByVal x As Integer, ...)
Signature means that the delegate must return and receive the same types than your function/method.
2º Call your function to update GUI using delegate. This for example inside your update GUI function:
If yourListBox.InvokeRequired Then
yourListBox.Invoke(New LogMessageExampleDelegate(AddressOf THE_FUNCTION_WHICH_UPDATES_THE_GUI_NAME), parameter_value)
Else
'Just call your function
End If
With, as example:
sub addToListBox(byval text as string)
myListBox.Items.add(text)
end sub
So your invoke would be:
If yourListBox.InvokeRequired Then
yourListBox.Invoke(New LogMessageExampleDelegate(AddressOf addToListBox), "Item 1")
Else
'Just call your function
addToListBox("Item 1")
End If
PS: I wrote it two times so hope I didn't mess up with something without noticing it.
I have replicated the code from the example to collect the result for code coverage from Here except that my code is vb.net
Here is my code
Imports Microsoft.VisualStudio.Coverage.Analysis
Module Module1
Sub Main()
Using info As CoverageInfo = CoverageInfo.CreateFromFile("C:MyFile\data.coverage")
Dim lines As New List(Of BlockLineRange)()
For Each [module] As ICoverageModule In info.Modules
Dim coverageBuffer As Byte() = [module].GetCoverageBuffer(Nothing)
Using reader As ISymbolReader = [module].Symbols.CreateReader()
Dim methodId As UInteger = 0
Dim MethodName As String = ""
Dim undecoratedMethodName As String = ""
Dim ClassName As String = ""
Dim NameSpaceName As String = ""
lines.Clear()
While reader.GetNextMethod(methodId, MethodName, undecoratedMethodName, ClassName, NameSpaceName, lines)
Dim stats As CoverageStatistics = CoverageInfo.GetMethodStatistics(coverageBuffer, lines)
Console.WriteLine("Method {0}{1}{2}{3}{4} has:" & NameSpaceName & ClassName & undecoratedMethodName)
Console.WriteLine(" blocks covered are {0}", stats.BlocksCovered)
End While
End Using
Next
End Using
End Sub
End Module
When I run this on the line for CreateFromFile i get a ImageNotFoundException
Image File "C:\SomeAddress\MyServer\UnitTest.dll" could not be found
I have already as per instructions added the neccessary dlls to my project copied and the other 2 as references.
And yet another tumbleweed moment....
Basically the problem was that folder containing my coverage file also had to contains all the dlls used within that assembely that tests were ran on in order to create that object.
hope this helps you if you ever stumbled over this issuen :)