HID variable not getting any info from definitions list - vb.net

I am currently using the Devices .NET library and this is the quick start guide that the Developer provided(I just modified it). Here is the code:
Private Shared Async Function InitializeHID() As Task
Try
Dim Logger = New DebugLogger()
Dim Tracer = New DebugTracer()
WindowsHidDeviceFactory.Register(Logger, Tracer)
WindowsUsbDeviceFactory.Register(Logger, Tracer)
Dim deviceDefinitions = New List(Of FilterDeviceDefinition) From {
New FilterDeviceDefinition With {
.DeviceType = DeviceType.Hid,
.VendorId = &H25A7,
.ProductId = &H2410
}
}
Dim devices = Await DeviceManager.Current.GetDevicesAsync(deviceDefinitions)
Dim anotherDevice = devices.FirstOrDefault()
Await anotherDevice.InitializeAsync()
Dim buffer = New Byte(64) {}
buffer(0) = &H3F
buffer(1) = &H23
buffer(2) = &H23
Dim readBuffer = Await anotherDevice.WriteAndReadAsync(buffer)
Debug.WriteLine("Success")
Catch ex As Exception
Debug.WriteLine("false")
End Try
End Function
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim temp = InitializeHID()
End Sub
I am running into the issue where the devices variable is getting nothing so therefore it just writes false instead of sending the bytes and writing success.
Please help!

Related

how to use ZoomNet DownloadFileAsync

I'm using a Nuget package Jericho /ZoomNet, trying to download a zoom recording (mp4) [winform App]
I'm not sure how the DownloadFileAsync() works to save the File from the Stream, I keep getting task cancelled exception
Can you point to any similar examples ?
UPDATE
So i talked to the Author of the package,
he made a beta release to download large files more efficiently, and also showed me you can add your own client object to control the timeout according to file size, also using the ConfigureAwait(False) was necessary.
Dim myHttpClient = New HttpClient() With {
.Timeout = TimeSpan.FromMinutes(10) }
Dim azoomClient = New ZoomClient(connectionInfo,
myHttpClient)
Dim sourceStream = Await
azoomClient.CloudRecordings.DownloadFileAsync(fdownloadFileName, ct).ConfigureAwait(False)
Using outStream = File.OpenWrite(DestFileName)
sourceStream.CopyTo(outStream)
End Using
This is the code I've tried
Private azoomClient = New ZoomClient(connectionInfo)
Dim fdownloadFileName As String = "c:\zoomrec1.mp4"
Dim ct As New Threading.CancellationToken
Dim sourceStream As Stream
sourceStream = Await azoomClient.CloudRecordings.DownloadFileAsync(fdownloadFileName, ct).ConfigureAwait(False)
DumpStream(sourceStream, DestFileName)
Private Async Function DumpStream(ByVal outStream As Stream, ByVal outputFileName As String) As Task
Try
' Dump the contents of a stream to a file
outStream.Flush()
Dim SavePos As Long = outStream.Position ' Save the original position in the stream
outStream.Seek(0, SeekOrigin.Begin)
Dim f As Stream = File.OpenWrite(outputFileName)
CopyStream(outStream, f)
outStream.Position = SavePos ' Go back to the original postion in the stream
f.Close()
Catch ex As Exception
MessageBox.Show("Error:DumpStream()>" & ex.Message)
End Try
End Function
Public Shared Sub CopyStream(ByVal input As Stream, ByVal output As Stream)
Try
' Copy the contents of one stream to another stream
Dim buf As Byte() = New Byte(8 * 1024 - 1) {} ' A buffer for storing data while copying
Dim len As Integer
len = input.Read(buf, 0, buf.Length)
While len > 0
output.Write(buf, 0, len)
len = input.Read(buf, 0, buf.Length)
End While
Catch ex As Exception
MessageBox.Show("Error:CopyStream()>" & ex.Message)
End Try
End Sub
'''
i can get the download url filename with this call,
'''
Dim apiKey = "abc" Dim apiSecret = "123"
Dim connectionInfo As New JwtConnectionInfo(apiKey, apiSecret)
Dim v As Object = azoomClient.CloudRecordings.GetRecordingInformationAsync(MeetingID)
Dim modelsRecording = Await v
downloadFileName = CStr(modelsRecording.RecordingFiles.Where(Function(z)
z.FileType = Models.RecordingFileType.Video)(0).DownloadUrl)
'''
I updated the code above with a working solution.

Track upload progress in Azure Blob Storage

I am building a file upload function to Microsoft Azure Blob Storage using VB.Net. Is there a way to track the progress of data transfer without using the Data Transfer Library of Microsoft? Here's my code:
Public Function isUploaded(ByVal filename As String) As Boolean
Try
Dim connectionString As String = "Connection String Here"
Dim containerName As String = "uploads"
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(connectionString)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim container As CloudBlobContainer = blobClient.GetContainerReference(containerName)
Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference(Path.GetFileName(filename).ToString)
Using FileStream = System.IO.File.OpenRead(filename)
blockBlob.UploadFromStream(FileStream)
Return True
End Using
Catch ex As Exception
Return False
MsgBox(ex.Message)
End Try
End Function
If you want to know how many bytes have been uploaded, you can use the method UploadFromStreamAsync in the sdk Microsoft.Azure.Storage.Blob. It will process the class StorageProgress which holds information about the progress data transfers for both request and response streams in a single operation.
For example
Sub Main()
Dim fileName As String = "D:\\help.txt"
Dim result = isUploaded(fileName).Result
Console.WriteLine(result)
Console.ReadLine()
End Sub
Public Async Function isUploaded(ByVal filename As String) As Task(Of Boolean)
Try
Dim connectionString As String = ""
Dim containerName As String = "test"
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(connectionString)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim container As CloudBlobContainer = blobClient.GetContainerReference(containerName)
Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference(Path.GetFileName(filename).ToString)
// Define the function how to handle the infromation
Dim handelr As Action(Of StorageProgress) = Sub(progress) Console.WriteLine("Progress: {0} bytes transferred", progress.BytesTransferred)
Dim progressHandler As IProgress(Of StorageProgress) = New Progress(Of StorageProgress)(handelr)
Dim cancellationToken As CancellationToken = New CancellationToken()
Using FileStream = File.OpenRead(filename)
Await blockBlob.UploadFromStreamAsync(FileStream,
New AccessCondition(),
New BlobRequestOptions(),
New OperationContext(),
progressHandler,
cancellationToken)
Return True
End Using
Catch ex As Exception
Return False
MsgBox(ex.Message)
End Try
End Function

How should I generate a "secret" code for my two factor authentication system?

I am only doing this as a method to secure a third party product that does not have a native way of requesting and setting up 2FA. Essentially this creates a request that is sent to IT to have them manually add the secret key to a users profile when requested.
How should I generate a "secret" code for my two factor authentication system?
I'm using the QRCoder package to generate a nice displayable QR Code for my userbase. And it works great in the Microsoft Authenticator app, but both Authy and Google fail.
I suppose my random secret generator function is to blame?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim generator As OneTimePassword = New OneTimePassword() With {
.Secret = GenerateRandomString(16),
.Issuer = "My Site",
.Label = "My Service",
.Type = OneTimePassword.OneTimePasswordAuthType.TOTP
}
Dim payload As String = generator.ToString()
Dim qrGenerator As QRCodeGenerator = New QRCodeGenerator()
Dim qrCodeData As QRCodeData = qrGenerator.CreateQrCode(payload, QRCodeGenerator.ECCLevel.Q)
Dim qrCode As QRCode = New QRCode(qrCodeData)
LiteralQRCode.Text = generator.Secret
Dim imgBarCode As New System.Web.UI.WebControls.Image()
imgBarCode.Height = 300
imgBarCode.Width = 300
Using bitMap As Bitmap = qrCode.GetGraphic(20)
Using ms As New MemoryStream()
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Dim byteImage As Byte() = ms.ToArray()
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage)
End Using
plBarCode.Controls.Add(imgBarCode)
End Using
End Sub
Public Function GenerateRandomString(ByRef iLength As Integer) As String
Dim rdm As New Random()
Dim allowChrs() As Char = "ABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
Dim sResult As String = ""
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End Function
I ended up using OtpNet and using their Base32Encode function to get what I needed.
Hopefully this will help the next person who is attempting to work on a project that isn't exactly conventional.
Dim totp = KeyGeneration.GenerateRandomKey()
Dim generator As OneTimePassword = New OneTimePassword() With {
.Secret = Base32Encoding.ToString(totp),
.Issuer = "My Site",
.Label = "My Service",
.Type = OneTimePassword.OneTimePasswordAuthType.TOTP
}

File upload using Threading

I have written a code to upload a file using thread.I have place a simple file upload control and a button on a page.The code looks like this-
Protected Sub btnUpload_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles btnUpload.Click
Dim timeStart As TimeSpan = Nothing
Dim timeEnd As TimeSpan = Nothing
Dim timeDiff As TimeSpan = Nothing
Dim ex As Exception = Nothing
Dim FileNameWithoutExtension As String = String.Empty
Try
Dim objTh As Thread = Nothing
objTh = New Thread(AddressOf SaveFileByBuffering)
timeStart = DateTime.Now.TimeOfDay
objTh.IsBackground = True
FileNameWithoutExtension = System.IO.Path.GetFileName(FldUploadThreading.FileName)
objTh.Start("New_" + FileNameWithoutExtension)
objTh.Name = "ARAThreadFileBuffer"
objTh.Join()
timeEnd = DateTime.Now.TimeOfDay
timeDiff = timeEnd - timeStart
Catch exThAbort As ThreadAbortException
ex = exThAbort
Catch exTh As ThreadStartException
ex = exTh
Catch exCommon As Exception
ex = exCommon
End Try
End Sub
the method to be called using thread:
Public Function SaveFileByBuffering(ByVal lstrFilePath As String)
Dim bufferSize As Integer = 512
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim pathUrl As String = ConfigurationManager.AppSettings("strFilePath").ToString()
Dim uploadObj As UploadDetail = New UploadDetail()
uploadObj.IsReady = True
uploadObj.FileName = lstrFilePath
uploadObj.ContentLength = Me.FldUploadThreading.PostedFile.ContentLength
Me.Session("UploadXDetail") = uploadObj
Dim Upload As UploadDetail = DirectCast(Me.Session("UploadXDetail"), UploadDetail)
Dim fileName As String = Path.GetFileName(Me.FldUploadThreading.PostedFile.FileName)
Using fs As New FileStream(Path.Combine(pathUrl, lstrFilePath), FileMode.Create)
While Upload.UploadedLength < Upload.ContentLength
Dim bytes As Integer = Me.FldUploadThreading.PostedFile.InputStream.Read(buffer, 0, bufferSize)
fs.Write(buffer, 0, bytes)
Upload.UploadedLength += bytes
End While
End Using
End Function
There are two issues:
When some one clicks on the same button simultaneously the thread behavior works in a different way , some time page crashes.
When this process i have tested on multiuser environment with 60 users and file size is 25 MB each user the page crashed.
I have .net 3.5 so i have no choice with advance version of file upload in 2010 or later version.

System.FormatException On ConvertFromBase64String

This is such a great place to ask questions!
I'm facing one problem.
I'm trying to send an image from an AutoIT client over to a server that is written in VB.NET
Here is the code for the AutoIT Client:
TCPStartup()
$MainSocket = TCPConnect("127.0.0.1", 9832)
$PATH = _ScreenCapture_Capture("")
$Data2Send = "RemoteDESK|" & _Base64Encode(HBITMAP_To_Bytes($PATH)) & "<EOF>"
TCPSend($MainSocket, $Data2Send)
And here is the code for the VB.NET server:
Data handler:
Private Sub GotInfo(ByVal Data As String, ByVal Sender As Socket)
Dim Cut() As String = Data.Split("|")
Select Case Cut(0)
Case "RemoteDESK"
Dim ImgString As String = Cut(1)
PictureBox1.Image = B64ToImage(ImgString)
End Select
End Sub
Base 64 String to Image Fucntion:
Private Function B64ToImage(ByVal B64 As String) As Image
Dim ByAr() As Byte = Convert.FromBase64String(B64) 'Exception Happens here
Dim img As Image
Dim MS As New MemoryStream(ByAr)
Try
img = Image.FromStream(MS)
Catch ex As Exception
Return Nothing
End Try
Return img
End Function
The OnReceive Sub:
Private Sub OnReceive(ByVal ar As IAsyncResult)
Dim Content As String = String.Empty
Dim State As StateObject = DirectCast(ar.AsyncState, StateObject)
Dim Handler As Socket = State._MySocket
Try
Dim BytesRead As Integer = Handler.EndReceive(ar)
If BytesRead > 0 Then
State._SB.Append(Encoding.ASCII.GetString(State.Data))
Content = State._SB.ToString
If Content.IndexOf("<EOF>") > -1 Then
Dim ReadContent As String = Content.Remove(Content.IndexOf("<EOF>"))
RaiseEvent GotInfo(ReadContent, State._MySocket)
Else
Handler.BeginReceive(State.Data, 0, State.BufferSize, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), State)
End If
End If
Catch ex As Exception
RaiseEvent ClientDC(Handler)
End Try
End Sub
Alright, so now I used a text comparing tool, and every time on line 53, the received string has changed, as in the the 2 lines of text are on the same line compared to the autoit's output.
The autoit output is the readable one.