Uploading to dropbox using dropnet - dropbox

I started to develop a project to create some dll to comunicate with Dropbox (Desktop).
After searching a while in google I found dropnet and started to use it.
I have two problems with this library on accessing the token and when I'm doing an upload.
Code:
Dim client As DropNetClient
If Not dropboxLoggedIn Then
client = New DropNetClient("XXXXXXXXXXXX", "YYYYYYYYYY")
client.UseSandbox = True
Dim token As UserLogin
Dim url As String = ""
Try
token = client.GetToken()
url = client.BuildAuthorizeUrl()
Dim aw As New AuthorizationWindow(url)
aw.ShowDialog()
If (Not dropboxLoggedIn) Then
client.GetAccessToken()
dropboxAsecret = client.UserLogin.Secret
dropboxAtoken = client.UserLogin.Token
Else
client.UserLogin.Token = dropboxAtoken
client.UserLogin.Secret = dropboxAsecret
End If
dropboxLoggedIn = True
Dim rawData As Byte() = File.ReadAllBytes("c:\users\mysuser\Pictures\anypic.JPG")
Dim result As MetaData = client.UploadFile("/", "anypic.JPG", rawData)
Catch ex As DropNet.Exceptions.DropboxException
MessageBox.Show(ex.Message)
End Try
Else
Try
client = New DropNetClient("XXXXXXXXXXXX", "YYYYYYYYYY", dropboxAtoken, dropboxAsecret)
client.UseSandbox = True
Dim rawData As Byte() = File.ReadAllBytes("c:\users\mysuser\Pictures\anypic.JPG")
Dim result As MetaData = client.UploadFile("/", "anypic.JPG", rawData)
Catch ex As DropNet.Exceptions.DropboxException
MessageBox.Show(ex.Message)
End Try
End If
So, after I do an upload nothing goes to dropbox folder. The result has nothing in properties. Is strange because no error is given.
Also, GetAccessToken not always work.
Can anyone help please?

Related

Acessing Google Calendar API from Windows Service

I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})

VB.NET Crawler can't handle Single Page Applications such as AngularJS

I have an existing web crawler (WinForms) developed using VB.NET for our SEOs which utilizes Web Requests. The application works fine on a regular website but when I try to crawl SPA sites (Single Page Applications), the application can't get a proper response.
Dim siteBody As String = String.Empty
Dim cleanedURL As String
Dim wRequest As System.Net.HttpwRequestuest
Dim wResponse As System.Net.HttpwResponse
Dim rStream As System.IO.Stream
Dim reader As System.IO.StreamReader
Try
wRequest = Nothing
wResponse = Nothing
rStream = Nothing
wRequest = HttpwRequestuest.Create(urlList(i)) 'URL is being passed
wRequest.Credentials = System.Net.CredentialCache.DefaultCredentials
wRequest.UserAgent = "DummyValue"
wRequest.AllowAutoRedirect = False
wResponse = wRequest.GetResponse()
rStream = wResponse.GetResponseStream
reader = New System.IO.StreamReader(rStream)
siteBody = reader.ReadToEnd
reader.Close()
wResponse.Close()
Catch ex As Exception
End Try
Dim passedBody = siteBody 'EMPTY RESULT
Based on the result, we will extract data and check for links and their status codes.

Dropnet code in vb not working

I'm trying to use dropnet for file upload on Dropbox in vb, but does not work. Results the following error: Received Response [Unauthorized]: Expected to see [OK]. The HTTP response was [{"error": "Request token not found."}]
Here is my code:
_client = New DropNetClient("xxxxxxx", "xxxxxxx")
Dim login As UserLogin = _client.GetToken()
_client.UserLogin = login
Dim url = _client.BuildAuthorizeUrl()
Process.Start(url)
Dim tokenAcess = _client.GetAccessToken()
_client.GetAccessTokenAsync(Function(accessToken)
_client = New DropNetClient("xxxxxx", "xxxxxx", tokenAcess)
End Function, Function([error]) MessageBox.Show([error].Message)
End Function)
Try
Dim rawData As Byte() = File.ReadAllBytes("c:\image.png")
Dim result As MetaData = _client.UploadFile("/", "image.png", rawData)
MessageBox.Show("Successfully uploaded to Dropbox.", "Uploaded to Dropbox")
Catch dropboxEx As Exception
MessageBox.Show("Error: " + dropboxEx.Message)
End Try

Big Query Pagination in vb.net

I am trying to page through BigQuery data with vb.net. I keep getting the same first page of data with my code. The way I understand, I need to set the pagetoken of the response to look at the next page.
With the following code, I only get the first page of data while never exiting my loop.
For the login I was setting the Oauthtoken of my queryrequest and that was getting the first page fine, but no attempt is made to page through the results that way.
I appreciate any lead in the right direction.
Dim DT As New DataTable
Dim ErrMessage As String = ""
Try
Dim INIT As New BigqueryService.Initializer
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add(BigqueryService.Scope.Bigquery)
Dim credential As UserCredential
Using stream As New FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, New FileDataStore("BQ.App")).Result
End Using
INIT.HttpClientInitializer = credential
Dim service As New BigqueryService(INIT)
Dim j As JobsResource = service.Jobs
Dim req As New QueryRequest
req.Query = tQuery.Text
Dim QRequest As JobsResource.QueryRequest = j.Query(req, projectId)
QRequest.OauthToken = MyAccessToken
Dim JOBID As String = QRequest.Execute.JobReference.JobId
Dim DATA = QRequest.Execute
Dim schema = DATA.Schema
For Each col In schema.Fields
DT.Columns.Add(col.Name)
Next
Dim page_Tok = ""
Dim rr As GetQueryResultsResponse
While True
Try
rr.PageToken = page_Tok
Catch ex As Exception
'No Token Yet
End Try
rr = j.GetQueryResults(projectId, JOBID).Execute
page_Tok = rr.PageToken
If rr.JobComplete = True Then
If page_Tok = "" Then
Exit While
End If
End If
Dim resp2 = rr.Rows
For Each row In resp2
Dim DR As DataRow = DT.NewRow
For f = 0 To row.F.Count - 1
Dim field = row.F
DR(f) = row.F(f).V
Next
DT.Rows.Add(DR)
Next
End While
Catch ex As Exception
ErrMessage = ex.Message
End Try
I'm not a VB expert, but you're not setting the page token in the GetQueryResultsRequest, you're setting it in the response. See https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/csharp/latest/classGoogle_1_1Apis_1_1Bigquery_1_1v2_1_1JobsResource_1_1GetQueryResultsRequest.html
I think that this will work:
req = j.GetQueryResults(projectId, JOBID)
req.PageToken = page_tok
rr = req.Execute

Check if SMTP is running or failed to send email

I am using SMTP server to send emails.
I would like to get an error message when the SMTP server is down or when the email was not delivered.
With DeliveryNotificationOptions.OnFailure I get an email that the email has not been delivered.
I would like to get an error. Is this possible?
How I can check if SMTP is running?
Here is the code I use:
Dim serverName As String = ""
Dim mailSenderInstance As SmtpClient = Nothing
Dim AnEmailMessage As New MailMessage
Dim sendersEmail As String = ""
Try
serverName = GetServerName("EMAIL_SERVER")
mailSenderInstance = New SmtpClient(serverName, 25)
sendersEmail = GetSendersEmail(msUserName)
AnEmailMessage.From = New MailAddress(sendersEmail)
'MAIL DETAILS
AnEmailMessage.Subject = "New Email"
AnEmailMessage.Body = "The Message"
AnEmailMessage.To.Add(anEmailAddress)
' Delivery notifications
AnEmailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
mailSenderInstance.UseDefaultCredentials = True 'False
mailSenderInstance.Send(AnEmailMessage)
Catch ex As System.Exception
MessageBox.Show(ex.ToString)
Finally
AnEmailMessage.Dispose()
mailSenderInstance.Dispose()
End Try
add another try catch block around your SMTP declaration
try
mailSenderInstance = New SmtpClient(serverName, 25)
catch ex as exception
msgbox( "Error creating SMTP connection: " & ex.message)
end try
regards
ok, you want to know the SMTP status. SMTP runs as a Service. I've written a function for you to know status of ANY service in the system. Add reference to "System.ServiceProcess" to your project.
''response: -1 = service missing, 0 = stopped or stopping, 1 = running
imports System.ServiceProcess ''add this at top
Private Function GetServiceStatus(ByVal svcName As String) As Integer
Dim retVal As Integer
Dim sc As New ServiceController(svcName)
Try
If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
retVal = 0
Else
retVal = 1
End If
Catch ex As Exception
retVal = -1
End Try
Return retVal
End Function
use it like this:
'' use taskManager to figure correct service name
dim svStatus as integer = GetServiceStatus("SMTP")
if svStatus <> 1 then
msgbox("Service not running or absent")
else
''write your send mail code here
end if
hope this will help you