How do you change the position of some text in VB - vb.net

I am programming an antivirus and really need to know how to change the position of the text that says "Infected!" and "Clean!"
I have not really tried much, because I took a tutorial on how to make it. I do not know how to program in Visual Basic. Sorry I know I'm a noob. Here is the code:
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim path As String = OpenFileDialog1.FileName
txtFilePath.Text = path
Dim sample As String
sample = md5_hash(path)
txtHash.Text = md5_hash(path)
Using f As System.IO.FileStream = System.IO.File.OpenRead("md5.txt")
Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
While Not s.EndOfStream
Dim line As String = s.ReadLine
If (line = sample) Then
lblResult.Text = "Infected!"
lblResult.ForeColor = Color.Red
Else
lblResult.Text = "Clean!"
lblResult.ForeColor = Color.Green
End If
End While
End Using
End Using
End If
End Sub
This is only a piece of the code. Please tell me how to fix this. I really could use some help. Thank You!

When trying to change the LOCATION of a label, use the
lblresult.Location = new Point(xCoord here, yCoord here)
Another way to adjust the position would be with the
lblresult.Top += How much you want it to be pushed down/up from its origin
Same is with the
lblresult.Right
lblresult.Left
lblresult.Bottom
Parameters. I think you should give more clear and detailed information about what you are trying to achieve and how one could help you

Related

How to detect graphic edges and only save that portion

I have a PictureBox, which I am using as a "Signature pad". The size is 475,175...If the user signs in a small area, I would like to only save the portion that has a signature mark. I am not sure where to begin. Any help would greatly be appreciated.
Private Sub btnSaveSignature_Click(sender As Object, e As EventArgs) Handles btnSaveSignature.Click
Dim signatureFileName = txtSignatureFileName.Text.Trim()
Dim signaturePath As String = Path.Combine(Application.StartupPath, txtSignatureFileName.Text & ".bmp")
If String.IsNullOrEmpty(signatureFileName) Then Return
If currentCurve < 0 OrElse signatureObject(currentCurve).Count = 0 Then Return
Using imgSignature As Bitmap = New Bitmap(pBoxSignature.Width, pBoxSignature.Height, PixelFormat.Format32bppRgb)
Using g As Graphics = Graphics.FromImage(imgSignature)
''BMPs require a White background. This line provide that.
g.FillRectangle(Brsh, 0, 0, pBoxSignature.Width, pBoxSignature.Height)
Call DrawSignature(g)
End Using
pBoxSignature.SizeMode = PictureBoxSizeMode.AutoSize
pBoxSavedSignature.SizeMode = PictureBoxSizeMode.AutoSize
imgSignature.Save(signaturePath, ImageFormat.Bmp)
pBoxSavedSignature.Image = New Bitmap(imgSignature)
End Using
End Sub
The above code is my Save to BMP routine. I would imagine any solution would need to go in this section.

Streamreader not reading all lines

I am working on a little tool that allows the selection of a single file. Where it will calculate the SHA2 hash and shows it in a simple GUI then takes the value and checks if that hash is listed in a blacklist text file. If it is listed then it will flag it as dirty, and if not it will pass it as clean.
But after hitting Google for hours on end and sifting through many online sources I decided let's just ask for advise and help.
That said while my program does work I seem to run into a problem, since no matter what I do ,it only reads the first line of my "blacklist" and refuses to read the whole list or to actually go line by line to see if there is a match.
No matter if I got 100 or 1 SHA2 hash in it.
So example if I were to have 5 files which I add to the so called blacklist. By pre-calculating their SHA2 value. Then no matter what my little tool will only flag one file which is blacklisted as a match.
Yet the moment I use the reset button and I select a different (also blacklisted) file, it passes it as clean while its not. As far as I can tell it is always the first SHA2 hash it seems to flag and ignoring the others. I personally think the program does not even check beyond the first hash.
Now the blacklist file is made up very simple.
*example:
1afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
2afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
4afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
....and so on.
So as you can see these fake example hashes are listed without any details.
Now my program is suppose to calculate the hash from a selected file.
Example:
somefile.exe (or any extension)
Its 5KB in size and its SHA2 value would be:
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
Well as you can see I took the third hash from the example list right?
Now if I select somefile.exe for scanning then it will pass it as clean. While its blacklisted. So if I move this hash to the first position. Then my little program does correctly flag it.
So long story short I assume that something is horrible wrong with my code, even though it seems to be working.
Anyway this is what I got so far:
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports MetroFramework.Forms
Public Class Fsmain
Function SHA256_SIG(ByVal file_name As String)
Return SHA256_engine("SHA-256", file_name)
End Function
Function SHA256_engine(ByRef hash_type As String, ByRef file_name As String)
Dim SIG
SIG = SHA256.Create()
Dim hashValue() As Byte
Dim filestream As FileStream = File.OpenRead(file_name)
filestream.Position = 0
hashValue = SIG.ComputeHash(filestream)
Dim hash_hex = PrintByteArray(hashValue)
Stream.Null.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByRef array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("x2")
Next i
Return hex_value.ToLower
End Function
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog = DialogResult.OK Then
Dim path As String = SampleFetch.FileName
Selectfile.Text = path
Dim Sample As String
Sample = SHA256_SIG(path)
SignatureREF.Text = SHA256_SIG(path)
Using f As System.IO.FileStream = System.IO.File.OpenRead("blacklist.txt")
Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
While Not s.EndOfStream
Dim line As String = s.ReadLine()
If (line = Sample) Then
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Dirty"
Resetme.Visible = True
RemoveMAL.Visible = True
Else
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Clean"
Resetme.Visible = True
RemoveMAL.Visible = False
End If
End While
End Using
End Using
End If
End Sub
Private Sub Fsmain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub Resetme_Click(sender As Object, e As EventArgs) Handles Resetme.Click
Selectfile.Text = Nothing
SignatureREF.Text = Nothing
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub RemoveMAL_Click(sender As Object, e As EventArgs) Handles RemoveMAL.Click
Dim ask As MsgBoxResult = MsgBox("Would you like to remove the Dirty file?", MsgBoxStyle.YesNo, MessageBoxIcon.None)
If ask = MsgBoxResult.Yes Then
System.IO.File.Delete(Selectfile.Text$)
Else
MsgBox("You sure you want to keep this file?")
Dim filepath As String = IO.Path.Combine("c:\Dirty\", "Dirty.txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(" " & DateTime.Now)
sw.WriteLine(" " & Selectfile.Text)
sw.WriteLine(" " & SignatureREF.Text)
sw.WriteLine(" " & Result.Text)
sw.WriteLine("-------------------")
sw.Close()
End Using
End If
End Sub
End Class
So if any of you guys can have a look at it and point out errors, or even can come up with a fix that would be great.
The simplest thing you can do to make your procedure working, is testing whether a defined condition is verified. Terminate the test if that condition is met.
Using a boolean variable, report the result of the test and take action accordingly.
The Using statement takes care of disposing the StreamReader.
You could modify you procedure this way:
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog <> DialogResult.OK Then Exit Sub
Dim sample As String = SHA256_SIG(SampleFetch.FileName)
SignatureREF.Text = sample
Dim isDirty As Boolean = False
Using reader As StreamReader = New StreamReader("blacklist.txt", True)
Dim line As String = String.Empty
While reader.Peek() > 0
line = reader.ReadLine()
If line = sample Then
isDirty = True
Exit While
End If
End While
End Using
If isDirty Then
'(...)
RemoveMAL.Visible = True
Result.Text = "Dirty"
Else
'(...)
RemoveMAL.Visible = False
Result.Text = "Clean"
End If
End Sub
If you have a String and you want to test whether it matches a line of a text file then you can use this simple one-liner:
If IO.File.ReadLines(filePath).Contains(myString) Then

RichTextBox find and color text visual basic

Hi i have a code for finding words from richtextbox and change font color, the code is working but i f i go back and edit the previous text to something that i don't want to color, the color doesn't go away. here is my code
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Dim S As Integer = RichTextBox1.SelectionStart
Dim html() As String = {"<!DOCTYPE html>", "<html>", "</html>", "<head>", "</head>", "<body>", "</body>", "pre>", "</pre>", "<!DOCTYPE>", "<title>", "</title>", "<a>",
"<abbr>", "<address>", "<area>", "<article>", "<aside>", "<audio>", "<acronym>", "<applet>", "<b>", "<base>", "<bdi>", "<bdo>", "<blockquote>", "<body>", "<br>", "<button>", "<basefont>", "<bgsound>", "<big>", "<blink>"}
For i As Integer = 0 To html.Length - 1
Dim str As String = html(i)
Dim start As Integer = S - str.Length - 1
If (start >= 0) Then
If (RichTextBox1.Text.Substring(start, str.Length).ToLower.Equals(str)) Then
RichTextBox1.SelectionStart = start
RichTextBox1.SelectionLength = str.Length
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectionStart = S
RichTextBox1.SelectionLength = 0
End If
End If
Next
RichTextBox1.SelectionColor = RichTextBox1.ForeColor
End Sub
When i run the code provided by Воля Або Смерть the half of text is colored in different colors.
EDITED: if you want to extend the code to allow properties, the modification is very simple. Just check if the regualr expression match contains a space or not. If so, then look in the allowed array for the match without any regards to the properties, values, etc. Code modified, and image added.
I know you asked for solution to your approach, but I am advising another approach for what you want to accomplish.
You could easily overcome this problem if you used Regular Expression.
The idea is simple..
At the RichTextBox_TextChanged event, a regular expression match maker iterates through all text and looks for any HTML tag (one that begins with < and ends with >) regardless of the text in-between.
Then instead of looping through all valid HTML tags in your array, one simple line can easily tell if the array Contains the element or not.
Here is my (Tested & Working) Code..
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub RichTextBox1_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RichTextBox1.TextChanged
Dim current_cursor_position As Integer = Me.RichTextBox1.SelectionStart
'This is useful to get a hold of where is the current cursor at
'this will be needed once all coloring is done, and we need to return
Dim html() As String = {"<!DOCTYPE html>", "<html>", "</html>", "<head>", "</head>",
"<body>", "</body>", "pre>", "</pre>", "<!DOCTYPE>", "<title>",
"</title>", "<a>", "<abbr>", "<address>", "<area>", "<article>",
"<aside>", "<audio>", "<acronym>", "<applet>", "<b>", "<base>",
"<bdi>", "<bdo>", "<blockquote>", "<body>", "<br>", "<button>",
"<basefont>", "<bgsound>", "<big>", "<blink>", "<img>","</img>",
"<input>","</input>"}
Dim pattern As String = "<(.)*?>"
Dim matches As MatchCollection = Regex.Matches(Me.RichTextBox1.Text, pattern)
For Each match In matches
Me.RichTextBox1.Select(match.index, match.length)
Dim lookFor As String = match.ToString
If match.ToString.Contains(" ") Then 'Checking if tag contains properties
lookFor = match.ToString.Substring(0, match.ToString.IndexOf(" ")) & ">"
'This line will strip away any extra properties, values, and will
' close up the tag to be able to look for it in the allowed array
End If
If html.Contains(lookFor.ToString.ToLower) Then
'The tag is part of the allowed tags, and can be colored green.
Me.RichTextBox1.SelectionColor = Color.Green
Else
'This tag is not recognized, and shall be colored black..
Me.RichTextBox1.SelectionColor = Color.Black
End If
Next
Me.RichTextBox1.SelectionStart = current_cursor_position
'Returning cursor to its original position
Me.RichTextBox1.SelectionLength = 0
'De-Selecting text (if it was selected)
Me.RichTextBox1.SelectionColor = Color.Black
'new text will be colored black, until
'recognized as HTML tag.
End Sub
End Class
PS: you could also avoid expanding your html array of allowed elements, by simply using a regular expression to look for valid HTML tags (with flexibility of spaces between tags, properties and values, etc.
If you wish, I could elaborate on this.
You are actually pretty close. Take the RichTextBox1.SelectionColor = RichTextBox1.ForeColor line out of the loop and you're golden.
For Each elem As String In html
Dim start As Integer = S - elem.Length - 1
If (start >= 0) Then
If (RichTextBox1.Text.Substring(start, elem.Length).ToLower.Equals(elem)) Then
RichTextBox1.SelectionStart = start
RichTextBox1.SelectionLength = elem.Length
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectionStart = S
RichTextBox1.SelectionLength = 0
End If
End If
Next
RichTextBox1.SelectionColor = RichTextBox1.ForeColor

VB.NET StreamReader Only Returning One Char On ReadLine/Initialization Error?

I am having a slight mishap in my vb.net (.NET Framework 4.5) app. On startup with this code, nothing changes, and when I trigger the event later to change label11, I only get the letter e, and I can't for the life of my figure out what is wrong with the code. The file is encoded in UTF-8 I believe, but changing the encoding doesn't seem to help. steamDisplayName, steamID64, and steamID32 are defined as strings at the beginning of the program. Here is my code that is executed on startup:
Private Sub mainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\Program Files (x86)\Steam\config\loginusers.vdf")
steamDisplayName = reader.ReadLine(3)
steamDisplayName = steamDisplayName.Replace(Chr(34), "")
steamDisplayName = steamDisplayName.Replace("PersonaName", "")
steamID64 = reader.ReadLine(5)
steamID64 = steamID64.Replace(Chr(34), "")
steamID32 = steamID64.Substring(0, 3) - 61197960265728
Label11.Text = "Welcome, " + steamDisplayName
My.Settings.steamID = steamID32
reader.Close()
End Sub
And here is my C:\Program Files (x86)\Steam\config\loginusers.vdf:
"users"
{
"76561198041432370"
{
"AccountName" "snip"
"PersonaName" "tsunami"
"RememberPassword" "1"
"Timestamp" "1407351554"
"WantsOfflineMode" "0"
}
}
This is NOT a code writing service, however, the code below should help you, it's completely untested, so please check it carefully first.
Private Sub mainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lines As New System.IO.File.ReadAllLines("C:\Program Files (x86)\Steam\config\loginusers.vdf")
Dim id As Long = 0
For Each line in lines
If line.Contains("PersonalName") Then
Dim parts = line.Split(Chr(34), SplitOptions.RemoveEmptyEntries)
steamDisplayName = parts(1)
ElseIf Long.TryParse(line.Trim.Replace(Chr(34), String.Empty), id) Then
steamID64 = id
steamID32 = steamID64.Substring(0, 3) - 61197960265728 ' What is this for?!
Label11.Text = "Welcome, " & steamDisplayName
My.Settings.steamID = steamID32
Next
End Sub
If Dharman could stop editing my posts from 9 years ago, it would be appreciated.

Youtube API - uploading large file using vb.net

I am trying to upload a large (4MB+) file to youtube using the API in VB.NET.
Smaller files upload fine, but anything larger than about 4MB gives an error which (I think) is actually related to a timeout: The request was aborted: The request was canceled.
I have read and re-read the API doco, googled, etc looking for an example in VB.NET, but nothing seems to be out there for vb.net
A few coders have hit the same problem and the responses have all been around c# or Java - neither of which I am familiar with.
I tried different combinations of the settings.timeout and settings.maximum, but it does not seem to make a difference
Current code is:
Sub UploadYouTube(ByVal sSourceFile As String, ByVal sTitle As String, ByVal sMediaCategory As String, ByVal sDesc As String)
Dim uSettings As YouTubeRequestSettings, uRequest As YouTubeRequest, newVideo As Video, CreatedVideo As Video, VideoId As String
Dim vContentType As String = "video"
Try
uSettings = New YouTubeRequestSettings(, , , )
uRequest = New YouTubeRequest(uSettings)
newVideo = New Video()
newVideo.Title = sTitle '"Test";
newVideo.Tags.Add(New MediaCategory("Education", YouTubeNameTable.CategorySchema))
newVideo.Description = sDesc '"Testing Testing Testing"
newVideo.YouTubeEntry.Private = False
uRequest.Settings.Timeout = 60 * 60 * 1000
uRequest.Settings.Maximum = 2000000000
' Determine the content type
If sSourceFile.EndsWith(".mov") Then
vContentType = "video/quicktime"
ElseIf sSourceFile.EndsWith(".avi") Or sSourceFile.EndsWith(".mpg") Or sSourceFile.EndsWith(".mpeg") Then
vContentType = "video/mpeg"
ElseIf sSourceFile.EndsWith(".wmv") Then
vContentType = "video/x-ms-wmv"
ElseIf sSourceFile.EndsWith(".m4v") Then
vContentType = "video/m4v"
ElseIf sSourceFile.EndsWith(".mp4") Then
vContentType = "video/mp4"
ElseIf sSourceFile.EndsWith(".3gp") Then
vContentType = "video/3gpp"
End If
newVideo.YouTubeEntry.MediaSource = New MediaFileSource(sSourceFile, vContentType)
CreatedVideo = uRequest.Upload(newVideo)
VideoId = CreatedVideo.VideoId
' Save the video Id to the database!
Catch ex As Exception
debug.print("Error. MainModule.Main. " & ex.Message, 5)
End Try
End Sub
Any help is greatly appreciated
Tony
Python example : https://github.com/Mathieu69/Pitivi_Gargamel/blob/upload_merger/pitivi/uploader.py did that 3 months ago, hope it helps.
I tried to solve the timeout problem by using a backgroundworker. It works, sort of. It doesn't appear to actually be working in the background. I would think the RunWorkerAsync would start, move on to the next command, and postback. Instead it just hangs for a few minutes like it's uploading the whole 75MB file, then posts back successful. If I take away the backgroundworker and just execute the upload however, it fails like yours did. Here's my code that kind of works.
Sub up_load(s As Object, e As EventArgs)
Dim worker As BackgroundWorker = New BackgroundWorker
worker.WorkerReportsProgress = True
worker.WorkerSupportsCancellation = True
AddHandler (worker.DoWork), AddressOf begin_upload
worker.RunWorkerAsync()
lblmsg.Text = "Successfully initiated upload"
End Sub
Sub begin_upload(s As Object, e As DoWorkEventArgs)
Dim request As New YouTubeRequest(settings)
Dim vidupload As New Video()
vidupload.Title = "My Big Test Movie"
vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
vidupload.Keywords = "church, jesus"
vidupload.Description = "See the entire video"
vidupload.YouTubeEntry.Private = False
vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")
Dim createdVideo As Video = Request.Upload(vidupload)
End Sub