Track upload progress in Azure Blob Storage - vb.net

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

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.

How do I insert new sheet in Existing google spreadsheet using vb.net?

I am manage to create spreadsheet on google drive using following code.
Now I want to add new sheets in that created spreadsheet.
When I Create new spreadsheet , it contains default sheet having name Sheet1 but I want to rename that sheet or insert more than one sheets in Spreadsheet
Public Function Create(ByVal FileName As String) As String
Try
Dim service = GetGoogleAPPDriveService()
Dim fileMetadata = New Google.Apis.Drive.v3.Data.File()
fileMetadata.Name = FileName
fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet"
Dim request As FilesResource.CreateRequest = service.Files.Create(fileMetadata)
request.SupportsTeamDrives = True
request.Fields = "id"
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllcertification)
Dim file = request.Execute
Return file.Id
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPDriveService() As DriveService
Try
Dim Scopes1 As String() = {DriveService.Scope.Drive, DriveService.Scope.DriveFile}
Dim ClientId As String = ""
Dim ClientSecret As String = ""
Dim UserCredentials As UserCredential
Dim stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientId = GoogleClientSecrets.Load(stream).Secrets.ClientId
Dim stream1 = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
ClientSecret = GoogleClientSecrets.Load(stream1).Secrets.ClientSecret
Dim cs = New ClientSecrets()
cs.ClientId = ClientId
cs.ClientSecret = ClientSecret
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, Scopes1, Environment.UserName,
CancellationToken.None, New FileDataStore("MyAppsToken", True)).Result
Dim service = New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function
Public Function AcceptAllcertification(ByVal sender As Object, ByVal Certification As X509Certificate, ByVal Chain As X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
You need to use the Sheets API for that. Have a look at the AddSheetRequest
Its hard to identify which request has to be used in .net from json file .
I succeed to add sheet in existing Spread sheet . Here I am put vb.net code if any one needed
Public Function Addsheet(ByVal FileId As String, ByVal sheetName As String) As String
Try
Dim serv = GetGoogleAPPSheetService()
Dim updatesheet = New BatchUpdateSpreadsheetRequest
Dim Req_Request As Request = New Request
Dim Req_AddSheet As New AddSheetRequest
Dim prop As New SheetProperties
prop.Title = sheetName
Req_AddSheet.Properties = prop
Req_Request.AddSheet = Req_AddSheet
Dim IList_req As IList(Of Request)
Dim List_req1 = New List(Of Request)
List_req1.Add(Req_Request)
IList_req = List_req1.ToList
updatesheet.Requests = IList_req
Dim req = serv.Spreadsheets.BatchUpdate(updatesheet, FileId)
Dim response = req.Execute
Catch ex As Exception
Throw ex
End Try
End Function
Private Function GetGoogleAPPSheetService() As SheetsService
Try
Dim UserCredentials As UserCredential
Using stream = New FileStream("credentials.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "token.json" 'System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)
'credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json")
UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
End Using
Dim service = New SheetsService(New BaseClientService.Initializer() With {
.HttpClientInitializer = UserCredentials,
.ApplicationName = ApplicationName})
Return service
Catch ex As Exception
Throw ex
End Try
End Function

HID variable not getting any info from definitions list

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!

What is wrong with my code (VB. NET async wait and httplistener)

I am trying to run a httplistener in order to receive a call back from an web application
However the never goes past context = Await httpListener.GetContextAsync
I can telnet to the port of the listener and it responds.
Class SSO
Public Sub AuthorizeAsync()
Me.oAccessToken = Operations.AuthorizeAsync.Result
End Sub
'
Class Operations
Shared Async Function AuthorizeAsync() As Task(Of SSO.AccessToken)
Dim AccessToken As SSO.AccessToken
Dim AuthorizationCodeTask As Task(Of String)
Dim cts As New System.Threading.CancellationTokenSource
AuthorizationCodeTask = Operations.RunCallbackListenAsync(cts.Token)
Try
OpenAutorizationUrl()
Dim t As String
t = Await AuthorizationCodeTask
AccessToken = GetAccessToken(t)
Catch ex As Exception
logger.LogException(ex)
Throw ex
End Try
Return AccessToken
End Function
Private Shared Async Function RunCallbackListenAsync(ByVal cts As System.Threading.CancellationToken) As Task(Of String)
Dim retval As String = Nothing
Dim blGo As Boolean = True
Dim httpListener As New System.Net.HttpListener
httpListener.Prefixes.Add(My.Settings.APICallBack)
httpListener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous
httpListener.Start()
If httpListener.IsListening Then
Dim request As System.Net.HttpListenerRequest
Dim context As System.Net.HttpListenerContext
context = Await httpListener.GetContextAsync
While Not cts.IsCancellationRequested And blGo
context = Await httpListener.GetContextAsync
Try
If cts.IsCancellationRequested Then
context.Response.Abort()
End If
request = context.Request
Catch ex As Exception
logger.LogException(ex)
End Try
blGo = False
End While
If Not IsNothing(request) Then
retval = ProcessRequest(request)
Else
Throw New ApplicationException("RunCallbackListenAsync: The request is Nothing")
End If
httpListener.Close()
Else
Throw New ApplicationException("RunCallbackListenAsync: listener is not listening")
End If
Return retval
End Function
End class
what could by causing the blocking at context = Await httpListener.GetContextAsync?

The given credentials or configuration format does not fits to the storage provider (Sharpbox)

I am new to cloud storage, I encountered this error
The given credentials or configuration format does not fits to the storage provider
when I tried to read a txt file with token (uploadMe sub). I am using vb. Looking forward to your reply.
My code:
Dim ConsumerKey As String = "******************"
Dim ConsumerSecret As String = "*****************"
Dim config As DropBoxConfiguration = DropBoxConfiguration.GetStandardConfiguration()
Dim requestToken As DropBoxRequestToken
Private Sub AuthorizeMe()
config.AuthorizationCallBack = New Uri("http://www.google.com")
requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, ConsumerKey, ConsumerSecret)
Dim AuthorizationUrl As String = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken)
Process.Start(AuthorizationUrl)
End Sub
Private Sub saveMyAuth()
Dim accessToken As ICloudStorageAccessToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(config, ConsumerKey, ConsumerSecret, requestToken)
Dim DropboxStorage As New CloudStorage()
DropboxStorage.Open(config, accessToken)
Dim File As FileStream = New FileStream("c:\TEMP\MyToken.txt", FileMode.Create, System.IO.FileAccess.Write)
DropboxStorage.SerializeSecurityTokenToStream(requestToken, File)
File.Close()
End Sub
Private Sub uploadme()
Try
Dim configio As DropBoxConfiguration = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
Dim DropboxStorage As New CloudStorage()
Dim accessToken As ICloudStorageAccessToken
Using fs = File.Open("C:\TEMP\MyToken.txt", FileMode.Open, FileAccess.Read, FileShare.None)
accessToken = DropboxStorage.DeserializeSecurityToken(fs)
End Using
DropboxStorage.Open(configio, accessToken)
Dim srcFile = Environment.ExpandEnvironmentVariables("C:\TEMP\mysqlbackup.xml")
DropboxStorage.UploadFile(srcFile, "/")
DropboxStorage.Close()
Catch ex As Exception
Console.Beep()
Console.Write(ex.Message, "")
End Try
End Sub