Visual Basic time synchronizing - vb.net

I am working oin a project in vb.net although I am not an expert in it, I just used it because U think it is the best for this kind of problem.
I have a project with two buttons and a label; first button is for sync windows date from a server and the other is to change the windows date to (2014, 11, 16). I am doing this because some programs I have doesn't run unless the date is this one and as you know browser must be the real time to run this is the idea of this project.
The second button is working perfectly, but the sync date button doesn't work and throws this error in my label
No connection because the target machine refused to connect
Here is my function and my server ip
Public Function GetNISTTime(ByVal host As String) As String
Dim timeStr As String = ""
Try
Dim reader As New StreamReader(New TcpClient(host, 13).GetStream)
LastSysTime = DateTime.UtcNow()
timeStr = reader.ReadToEnd()
reader.Close()
Catch ex As SocketException
GetNISTTime = ex.Message
Exit Function
Catch ex As Exception
GetNISTTime = ex.Message
Exit Function
End Try
'Dim jd As Integer = Integer.Parse(timeStr.Substring(1, 5))
'Dim yr As Integer = Integer.Parse(timeStr.Substring(7, 2))
'Dim mo As Integer = Integer.Parse(timeStr.Substring(10, 2))
'Dim dy As Integer = Integer.Parse(timeStr.Substring(13, 2))
'Dim hr As Integer = Integer.Parse(timeStr.Substring(16, 2))
'Dim mm As Integer = Integer.Parse(timeStr.Substring(19, 2))
'Dim sc As Integer = Integer.Parse(timeStr.Substring(22, 2))
'Dim Temp As Integer = CInt(AscW(timeStr(7)))
Return timeStr ' New DateTime(yr + 2000, mo, dy, hr, mm, sc)
End Function
and the button
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
GetNISTTime("mail.harf.com.sa")
Label1.Text = GetNISTTime("mail.harf.com.sa").ToString
End Sub
I think the problem is because of the server but I didn't find any dns server that does sync successfully.
This is my program download link if you want to see the problem in with your eyes (you should run it as adminstrator)
http://www.mediafire.com/file/wfw5jpag8w2hofb/Release.rar/file
Also it must be dns in Saudi Arabia time zone

Your function call is not correct.
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
GetNISTTime("mail.harf.com.sa")
Label1.Text = GetNISTTime("mail.harf.com.sa").ToString
End Sub
should be:
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
Label1.Text = GetNISTTime("mail.harf.com.sa")
End Sub
GetNISTTime is a function that returns a string, so your original first line (GetNISTTime("mail.harf.com.sa")) does the work but nothing is done with the return value. Your original second line takes a return value that is a string and then tries to convert it to a string.
In addition, your function may not return anything if an error occurs. You have used a VBA style assignment in the catch block. Instead, try:
Public Function GetNISTTime(ByVal host As String) As String
Dim timeStr As String = ""
Try
Dim reader As New StreamReader(New TcpClient(host, 13).GetStream)
LastSysTime = DateTime.UtcNow()
timeStr = reader.ReadToEnd()
reader.Close()
Catch ex As SocketException
return ex.Message
Catch ex As Exception
Return ex.Message
End Try
'any other stuff
Return timeStr
End Function

so i did like what Visual Vincent say and this is my code after editing it
and it worked perfectly with me just need administrator permissions
code
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Runtime.InteropServices
Public Class Daytime
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim d As DateTime
d = "12:52:00"
Try
Microsoft.VisualBasic.TimeOfDay = d 'Your time...
Microsoft.VisualBasic.DateString = New Date(2014, 11, 16) 'The date...
Catch ex As Exception
'You might have to run as Administrator...?
End Try
End Sub
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
Process.Start("CMD", "/C net start w32time & w32tm /resync /force & pause")
End Sub
End Class

Related

how to create log in password in vb encrypted

Hi i have been searching the internet for 3 weeks now on how to create a log in interface with encrypted password . I was a to encrypt the text box for password but I dont know how to implement it . I am using linq to sql dbml to connect to my data based on text only I was able to get it can create but I want it to be more secure and more professionally looking with encrypted one. By the way I used wizard for creating database not hard coded it that is the way I know how to do it. I am totally noob in programming any help will do. Thanks
Public Class User_Log_In_v7
Dim admin As New GeneralsDataContext
Private Sub User_Log_InBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Validate()
Me.User_Log_InBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.User_Log_In_DataSet)
End Sub
Private Sub User_Log_In_v7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'User_Log_In_DataSet.User_Log_In' table. You can move, or remove it, as needed.
'Me.User_Log_InTableAdapter.Fill(Me.User_Log_In_DataSet.User_Log_In)
End Sub
Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogIn.Click
Try
Dim check = From Storage In admin.User_Log_Ins _
Where UsernameTextBox.Text = Storage.Username And PasswordTextBox.Text = Storage.Password
If Not check.Count = 0 Then
Membership_Information.Show()
Me.Hide()
UsernameTextBox.Text = ""
PasswordTextBox.Text = ""
Else
MsgBox("Please check username or password and try again", MsgBoxStyle.Exclamation, "")
UsernameTextBox.Text = ""
PasswordTextBox.Text = ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This is the code I can from another tutorial for encrypting
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Dim DES As New TripleDESCryptoServiceProvider
Dim MD5 As New MD5CryptoServiceProvider
'hash function
Function MD5Hash(value As String) As Byte()
Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function
'Encryption
Function Encrypt(input As String, Key As String) As String
DES.Key = MD5Hash(Key)
DES.Mode = CipherMode.ECB
Dim buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(input)
Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length))
End Function

FTP download files larger than 2GB (VB.net)

Missing last few bytes and file gets corrupted - bounty
I now added a bounty to solve this problem. I changed the integer types to int64 which seem to have solved part of the problem, but now when ever it finishes the download it sometimes misses the last 1-5 bytes, which in return corrupts the file, so it can't be unzipped. Is there another way of closing the stream so it ensures the files are fully downloaded, and avoid getting corrupted? I've since tried this simple code, but same problem happens.
Imports System.ComponentModel
Imports System.Net
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
Dim WithEvents WC As New WebClient
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
WC.DownloadFileAsync(New Uri("ftp://dmr-ftp-user:dmrpassword#5.44.137.84/ESStatistikListeModtag/ESStatistikListeModtag-20160327-094743.zip"), "C:\XML\ESStatistikListeModtag-20160327-094743.zip.zip")
End Sub
Private Sub WC_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles WC.DownloadProgressChanged
ProgressBar1.Value = e.ProgressPercentage
If e.ProgressPercentage = 100 Then
MsgBox("File download - 100%") 'This message box does trigger once the download is complete, but file is still corrupted.
End If
End Sub
Private Sub WC_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles WC.DownloadFileCompleted
MsgBox("Complete") ' This message box doesn't trigger!
End Sub
End Class
OLD QUESTION:
I'm trying to download a zip file from an FTP server with my vb.net application. My current source code is posted below. This works fine for smaller files, but when I exceed a limit of 2GB I get the following exception:
"Arithmetic operation resulted in an overflow"
It's a file with the size of about 2.5 GB and increasing slightly each weak (about 20 MB), so I need a solution which can handle large files, hopefully with no limit. Eventually I would like to unzip the file with the program too, so if you have any ideas for doing this, you can post this as well. Thanks!
Private Sub Download(ByVal filePath As String, ByVal fileName As String)
FTPSettings.IP = "0.0.0.0"
FTPSettings.UserID = "ftp-user"
FTPSettings.Password = "ftp-pass"
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Try
Dim outputStream As New FileStream(filePath + "\" + fileName, FileMode.Create)
reqFTP = DirectCast(FtpWebRequest.Create(New Uri("ftp://" + FTPSettings.IP + "/" + fileName)), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential(FTPSettings.UserID, FTPSettings.Password)
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
ftpStream = response.GetResponseStream()
Dim cl As Long = response.ContentLength
Dim bufferSize As Integer = 2048
Dim readCount As Int64
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim size As Int64
readCount = ftpStream.Read(buffer, 0, bufferSize)
While readCount > 0
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
If readCount = bufferSize Then
size += readCount
Label1.Text = size
Label1.Refresh()
End If
End While
ftpStream.Close()
outputStream.Close()
response.Close()
Catch ex As Exception
MsgBox(ex.Message)
If ftpStream IsNot Nothing Then
ftpStream.Close()
ftpStream.Dispose()
End If
Throw New Exception(ex.Message.ToString())
End Try
End Sub
Public NotInheritable Class FTPSettings
Private Sub New()
End Sub
Public Shared Property IP() As String
Get
Return m_IP
End Get
Set(ByVal value As String)
m_IP = value
End Set
End Property
Private Shared m_IP As String
Public Shared Property UserID() As String
Get
Return m_UserID
End Get
Set(ByVal value As String)
m_UserID = value
End Set
End Property
Private Shared m_UserID As String
Public Shared Property Password() As String
Get
Return m_Password
End Get
Set(ByVal value As String)
m_Password = value
End Set
End Property
Private Shared m_Password As String
End Class
End Class
I've had similar problems with WebClient before, specially if using it with the WithEvents statement.
See if re-writing your code like this solves the problem:
Imports System.ComponentModel
Imports System.Net
Public Class Form1
Private wc As New WebClient()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
wc = New WebClient()
AddHandler wc.DownloadProgressChanged, Sub(s As Object, ByVal e As DownloadProgressChangedEventArgs)
Me.Invoke(New MethodInvoker(Sub() ProgressBar1.Value = e.ProgressPercentage))
End Sub
AddHandler wc.DownloadFileCompleted, Sub(s As Object, e As ComponentModel.AsyncCompletedEventArgs)
MsgBox("Complete")
End Sub
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
wc.DownloadFileAsync(New Uri("ftp://dmr-ftp-user:dmrpassword#5.44.137.84/ESStatistikListeModtag/ESStatistikListeModtag-20160327-094743.zip"), "C:\XML\ESStatistikListeModtag-20160327-094743.zip.zip")
End Sub
End Class

Visual basic Windows forms BitArray convert to string

Hi I made a code and it outputs random characters and unknown symbols.
The code is:
Function ReceiveMessages() As String
Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
from = RemoteIpEndPoint.Address.ToString
Dim BitDet As BitArray
BitDet = New BitArray(receiveBytes)
Dim strReturnData As String = _
System.Text.Encoding.Unicode.GetString(receiveBytes)
rt = strReturnData
I don't think it is a problem with the receiving but it might.
This function is called by:
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
Try
receivingUdpClient = New System.Net.Sockets.UdpClient(11211)
Catch ex As Exception
End Try
ThreadReceive = _
New System.Threading.Thread(AddressOf ReceiveMessages)
ThreadReceive.Start()
End Sub
If you could help I would appreciate it.

Stuck on my Login Panel

It keeps returning null and I was hoping someone could clean it up for me and see if there is a simpler way to do this. I'm really wanting to start making my game.
Public Class frmLogin
Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
Application.Exit()
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text
If File.Exists(FILE_NAME) Then
Me.lblExists.Text = "Username has already been created!"
Return
End If
If txtCUser.Text.Length < 3 Then
Me.lblExists.Text = "Must have atleast 3 characters."
Return
End If
Dim writeFile As StreamWriter = File.CreateText("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text)
writeFile.WriteLine("User: " + Me.txtCUser.Text) ' user
writeFile.WriteLine("Pass: " + Me.txtCPass.Text) ' pass
writeFile.WriteLine("-------------------")
writeFile.Close()
End Sub
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) = False Then
Using sr As New StreamReader("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return (sr.ReadLine())
sr.Close()
End Using
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text
If File.Exists(FILE_NAME) And Me.txtPassword.Text = (GetLine(FILE_NAME, 2).Substring(6)) Then
Me.lblLoggedIn.Text = "Logged"
ElseIf File.Exists(FILE_NAME) = False Then
Me.lblLoggedIn.Text = "You must create an account! Navigate to TabPage2."
End If
End Sub
End Class
It would really help a lot. I just started vb not to long ago maybe about a week or two.
Three things. First, in GetLine() you're attempting to open the file if it does NOT exist; change from False to True. Second, you should open the file name that was passed in, not a hard-coded one that uses the value from a TextBox. Lastly, to get rid of the warning, you need to return something if the file does not exist:
Change GetLine() to:
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) Then
Using sr As New StreamReader(fileName)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return sr.ReadLine()
End Using
Else
Return "{File Not Found: " & fileName & "}"
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
*You were returning the exception as a string, so I followed that model with the file not found error. How will you know, though, if you have an actual error, or if the line in the file was exactly like the "error" being returned?

Chat system with one or two ways?

I'm trying con build a simple chat client/software (whole in on executable) wich start listen from the start on the port 5900 and when a client connect to that port the chat is established.
The problem is that only the client can chat to the server, the server cannot answer the client because the connection is working in one way.
The i've tried to connect from "server" to the client when it establishes a connection but the system crash warning me that the port is already on use.
This my code: (working in one way)
Imports System.Net.Sockets
Imports System.Text
Imports System.Reflection
Public Class frmComplete
Dim Data As Integer
Dim Message As String
Private sServer As TcpListener
Private sClient As New TcpClient
Private cServer As TcpListener
Private cClient As New TcpClient
Private cNick As String
Dim BufferSize(1024) As Byte
Private Delegate Sub MessageDelegate(ByVal Message As String)
Private Sub frmComplete_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
srvListen(5900)
btnSend.Enabled = False
End Sub
Private Sub OnServerConnect(ByVal AR As IAsyncResult)
sClient = sServer.EndAcceptTcpClient(AR)
sClient.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnRead, Nothing)
My.Computer.Audio.Play(Application.StartupPath & "\Connected.wav", AudioPlayMode.Background)
End Sub
Private Sub OnRead(ByVal AR As IAsyncResult)
Data = sClient.GetStream.EndRead(AR)
Message = Encoding.ASCII.GetString(BufferSize, 0, Data)
Dim Args As Object() = {Message}
Me.Invoke(New MessageDelegate(AddressOf PrintMessage), Args)
sClient.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnRead, Nothing)
End Sub
Private Sub PrintMessage(ByVal Message As String)
Try
txtChat.Text = txtChat.Text & Message & vbCrLf
My.Computer.Audio.Play(Application.StartupPath & "\Message.wav", AudioPlayMode.Background)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub srvListen(ByVal port As Integer)
Try
sServer = New TcpListener(System.Net.IPAddress.Any, 5900)
sServer.Start()
'THIS WILL RAISE THE EVENT WHEN A CLIENT IS CONNECTED
sServer.BeginAcceptTcpClient(AddressOf OnServerConnect, Nothing)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub txtMessage_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMessage.KeyDown
'FIXME (SOUND T_T)
If e.KeyCode = Keys.Enter Then
SendMessage(cNick & ":" & txtMessage.Text)
End If
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
ConnectToServer(txtIP.Text)
cNick = txtNickname.Text
txtNickname.Enabled = False
txtIP.Enabled = False
btnConnect.Enabled = False
End Sub
Private Sub ConnectToServer(ByVal ipadress As String)
Try
cClient.BeginConnect(ipadress, 5900, AddressOf OnClientConnect, Nothing)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub OnClientConnect(ByVal AR As IAsyncResult)
Try
cClient.EndConnect(AR)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If Not String.IsNullOrEmpty(txtMessage.Text) Then
txtChat.Text = txtChat.Text & "Me:" & txtMessage.Text & vbCrLf
SendMessage(cNick & ":" & txtMessage.Text)
End If
End Sub
Private Sub SendMessage(ByVal message As String)
If cClient.Connected = True Then
Dim Writer As New IO.StreamWriter(cClient.GetStream)
Writer.Write(message)
Writer.Flush()
End If
txtMessage.Text = ""
End Sub
Private Sub SendCommand(ByVal command As String)
If cClient.Connected = True Then
Dim Writer As New IO.StreamWriter(cClient.GetStream)
Writer.Write(command)
Writer.Flush()
End If
txtMessage.Text = ""
End Sub
Private Sub txtMessage_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMessage.TextChanged
If Not String.IsNullOrEmpty(txtMessage.Text) Then
btnSend.Enabled = True
Else
btnSend.Enabled = False
End If
End Sub
End Class
What I should do? use two ports? one for write and another to read? And if i need to conect multiple clients to one user? (remember the same exe is server/client)
Please help me =(
You aren't reading any data coming back from the Server. You'll notice in your OnServerConnect method you call the BeginRead -- you will also need to do this for your client in the OnClientConnect method, or you'll get a one way communication. Perhaps this is why you are not seeing any data coming through?
I'm guessing, when your Server sends back the data to the client, you aren't getting a hard-error, just no data.
Just glancing over your code I noticed that you have both a TcpClient and TcpListener for your client and server. You don't need this. Your SERVER will be the TcpListener, and your CLIENT will be the TcpClient. By asking if you should connect back on a different port from the server, you are shortchanging yourself of what the TCP connection really is. Once your TcpClient has connected to the TcpServer, your connection is established. There is no need further to attempt to connect.
You're client code should be something similar to:
Private Sub OnClientConnect(ByVal AR As IAsyncResult)
Try
cClient.EndConnect(AR)
sServer.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnClientRead, Nothing)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub OnClientRead(ByVal AR As IAsyncResult)
Data = sServer.GetStream.EndRead(AR)
Message = Encoding.ASCII.GetString(BufferSize, 0, Data)
Dim Args As Object() = {Message}
Me.Invoke(New MessageDelegate(AddressOf PrintMessage), Args)
sServer.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnClientRead, Nothing)
End Sub