Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute is not defined - vb.net

Using a script I found here Problem is it's for 2012 and I'm using 2008.
I've handled all of the personal stuff(connections, variables, URLS, etc.) But I keep getting an error when I try to run the script.
Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute is not defined
Using VB.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.ComponentModel
Imports System.Diagnostics
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Protected Sub SaveFile(ByVal url As String, ByVal localpath As String)
Dim loRequest As System.Net.HttpWebRequest
Dim loResponse As System.Net.HttpWebResponse
Dim loResponseStream As System.IO.Stream
Dim loFileStream As New System.IO.FileStream(localpath, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim laBytes(256) As Byte
Dim liCount As Integer = 1
Try
loRequest = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest)
loRequest.Credentials = System.Net.CredentialCache.DefaultCredentials
loRequest.Timeout = 600000
loRequest.Method = "GET"
loResponse = CType(loRequest.GetResponse, System.Net.HttpWebResponse)
loResponseStream = loResponse.GetResponseStream
Do While liCount > 0
liCount = loResponseStream.Read(laBytes, 0, 256)
loFileStream.Write(laBytes, 0, liCount)
Loop
loFileStream.Flush()
loFileStream.Close()
Catch ex As Exception
End Try
End Sub
Public Sub Main()
Dim url, destination As String
destination = Dts.Variables("Folder_Destination").Value.ToString + "\" + "Report_" + Dts.Variables("ReportParameter").Value.ToString + "_" + Format(Now, "yyyyMMdd") + ".xls"
url = "http://localhost:8080/ReportServer?/MyReports/SSIS_Execute_SSRS_Report&rs:Command=Render&Productkey=" + Dts.Variables("ReportParameter").Value.ToString + "&rs:Format=EXCEL"
SaveFile(url, destination)
Dts.TaskResult = ScriptResults.Success
End Sub
End Class

Figured it out.
The Addin.Addins have been deprecated.
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
is fine for 2010 but for 2008
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> _
is needed.
Hope that helps anyone else out.

I got the same error message trying to import an existing SSIS 2016 package into a new solution.
I found that when I created my new solution in VS/TFS it set the target server version to 2017.
I changed the TargetServerVersion back to 2016 and it now works.
In VS, Right click on Project > view Properties.
Look under Configuration properties > General > TargetServerVersion.

Related

What can I do to prohibit text splitting when extracting text from PDF file using iText7?

I have written a little VB.Net program to extract text and info from PDF file using iText7 API installed using Nuget.
When I run it, for a lot of strings, I get more than one string !
Example:
Left: 128,2880 /Right: 147,7406 /Top: 693,7059 /Bottom: 688,3118 /Text: [TRANSPO]
Left: 147,7384 /Right: 150,5556 /Top: 693,7059 /Bottom: 688,3118 /Text: [R]
Left: 150,4318 /Right: 153,0811 /Top: 693,7059 /Bottom: 688,3118 /Text: [T]
What can I do to prohibit text splitting ?
In example, the string is TRANSPORT and is equal of string displayed on second line in white cell.
I know that I can write a litte code to unsplit "badly" splitting strings; but in posting this question, I simply hope that iText7 can simply do it himself.
The complete program is following
Imports System.IO
Imports System.Net
Imports System.Runtime.InteropServices
Imports iText.Kernel.Pdf
Imports iText.Kernel.Pdf.Canvas.Parser
Imports iText.Kernel.Pdf.Canvas.Parser.Listener
Imports System.Text
Imports System.Text.RegularExpressions
Imports iText.StyledXmlParser.Jsoup.Nodes
Imports iText.Kernel.Utils
Imports iText.Kernel.Geom
Imports iText.Kernel.Pdf.Canvas.Parser.Data
Imports iText.Commons.Utils
Imports iText.IO.Util
Imports Org.BouncyCastle.Math.EC
Imports System.ComponentModel
Imports iText.StyledXmlParser.Jsoup
Module MainModule
Public Class XEventListener
Implements IEventListener
Private oInfoList As New List(Of TextRenderInfo)
Public Function getResultantTextWithPosition() As List(Of TextRenderInfo)
Return oInfoList
End Function
Private Sub RenderText(t As TextRenderInfo)
If t.GetText().Trim().Length() = 0 Then Return
oInfoList.Add(t)
End Sub
Public Sub EventOccurred(data As IEventData, type As EventType) Implements IEventListener.EventOccurred
Dim t As TextRenderInfo = data
t.PreserveGraphicsState()
Call RenderText(t)
End Sub
Public Function GetSupportedEvents() As ICollection(Of EventType) Implements IEventListener.GetSupportedEvents
Dim collection As New List(Of EventType)
collection.Add(EventType.RENDER_TEXT)
Return collection
End Function
End Class
Public Sub Main()
Dim sPdfFile as String = "CinéTéléRevue.2023-01-19.pdf"
Using oReader As PdfReader = New PdfReader(sPdfFile)
Using pdfDocument As PdfDocument = New PdfDocument(oReader)
For pageNum As Integer = 1 To pdfDocument.GetNumberOfPages
Dim page As PdfPage = pdfDocument.GetPage(pageNum)
Call ExtractPage(page)
Next pageNum
End Using
End Using
End Sub
Private Sub ExtractPage(page As PdfPage, sTitle As String)
Dim sNewPage As String = sPdfFile.Replace(".pdf", "") & "." & sTitle & ".pdf"
Using oWriter As New PdfWriter(sNewPage)
Using pdfDocument As New PdfDocument(oWriter)
pdfDocument.AddPage(page.CopyTo(pdfDocument))
pdfDocument.Close()
End Using
End Using
Dim listener As New XEventListener()
Dim processor As New PdfCanvasProcessor(listener)
processor.ProcessPageContent(page)
Dim t1 As TextRenderInfo
sNewPage = sPdfFile.Replace(".pdf", "") & "." & sTitle & ".info"
Using sw As New StreamWriter(sNewPage)
Dim result = listener.getResultantTextWithPosition()
For Each t As TextRenderInfo In result
Dim ascent As LineSegment = t.GetAscentLine()
Dim descent As LineSegment = t.GetDescentLine()
Dim initX As Single = descent.GetStartPoint().Get(0)
Dim initY As Single = descent.GetStartPoint().Get(1)
Dim endX As Single = ascent.GetEndPoint().Get(0)
Dim endY As Single = ascent.GetEndPoint().Get(1)
Dim rect As Rectangle = New Rectangle(initX, initY, endX - initX, endY - initY)
Dim iLeft As Single = rect.GetLeft()
Dim iRight As Single = rect.GetRight()
Dim iTop As Single = rect.GetTop()
Dim iBottom As Single = rect.GetBottom()
Dim sLine As String = ""
sLine &= "Left: " & iLeft.ToString("0.0000").PadLeft(10) & " /"
sLine &= "Right: " & iRight.ToString("0.0000").PadLeft(10) & " /"
sLine &= "Top: " & iTop.ToString("0.0000").PadLeft(10) & " /"
sLine &= "Bottom: " & iBottom.ToString("0.0000").PadLeft(10) & " /"
sLine &= "Text: [" & t.GetText() & "]"
sw.WriteLine(sLine)
Next
sw.Close()
End Using
End Sub
End Module

How to add thumbnailphoto to Active Directory user?

I am trying to use VB.Net and PowerShell to update AD photos (thumbnailphotos property). So I used straight PowerShell to do a one-time update of all users' thumbnailphoto property already and that worked. What I would like to do is do a night job that gets picture files that were modified or are new in the past 24 hours. Most parts of my code (getting the last 24 hour edited files and parsing the userlogin by querying an internal database) is working. The part that doesn't work is the PowerShell part that should update the photo.
Imports System.Collections.ObjectModel
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.IO
Imports System.Data.SqlClient
Imports System.Text
Module Module1
Sub Main()
'Read the number of files that are new in the past 24 hours
GetFiles()
Console.ReadLine()
End Sub
Private Sub GetFiles()
Dim directory = New DirectoryInfo("\\server\share")
Dim from_date As DateTime = DateTime.Now.AddDays(-7)
Dim to_date As DateTime = DateTime.Now
Dim files = directory.GetFiles().Where(Function(file) file.LastWriteTime >= from_date AndAlso file.LastWriteTime <= to_date)
'Test to see what file output we are getting
'===========================================
For Each file In files
'Console.WriteLine(file.ToString)
'Going to function to find user if file is not thumbs.db
If file.ToString <> "Thumbs.db" Then
FindUsername(file.ToString())
End If
Next
End Sub
Private Sub FindUsername(ByVal fileName As String)
'Calling function to find the user that has the picfile with this name
Dim userLogin As String = ""
Dim sqlConnection1 As New SqlConnection("Data Source=sqlserver;Initial Catalog=database;Integrated Security=False;User Id=user;Password=password;")
Dim cmd As New SqlCommand
Dim returnValue As Object
cmd.CommandText = "SELECT RTRIM(userLogin) AS [userLogin] FROM directory WHERE picfile='" + fileName + "'"
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
sqlConnection1.Open()
returnValue = cmd.ExecuteScalar()
'Console.WriteLine(returnValue.ToString + " " + fileName.ToString)
sqlConnection1.Close()
If returnValue IsNot Nothing Then
'Run script with powershell
updatePhotoInAD(returnValue.ToString, fileName.ToString)
End If
End Sub
Private Sub updatePhotoInAD(userLogin As String, fileName As String)
'Prepare pipeline for execution
Dim fileNamewithPath As String = "\\server\share\" + fileName
Dim commandString As String = String.Format("Set-UserPhoto " + "{0}" + " - PictureData([System.IO.File]::ReadAllBytes(" + "{1})", userLogin, fileNamewithPath)
Using PowerShellInstance As PowerShell = PowerShell.Create()
' use "AddScript" to add the contents of a script file to the end of the execution pipeline.
' use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript(commandString)
' invoke execution on the pipeline (ignore output)
PowerShellInstance.Invoke()
End Using
Console.WriteLine(userLogin + " " + fileName + " " + commandString)
End Sub
End Module

How to use Google.Apis.Analytics.v3 API with vb.net service app

I have managed to autenticate my self succesfully to google etc. but now I need help how to use Google.Apis.Analytics.v3 or Google.Apis.Analytics.v3.Data dll to retrive data. for example I need last month vistors. So far I have this:
Imports System.Security.Cryptography.X509Certificates
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Imports Google.Apis.Analytics.v3
Imports Google.Apis.Analytics.v3.Data
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Services
Imports Google.Apis.Util
Public Class gaimport
Inherits System.Web.UI.Page
Public Shared Sub Main(sender As Object, e As EventArgs)
Dim serviceAccountEmail As String = "xxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com"
Dim userEmail As String = "xxxxx#gmail.com"
Dim certificate As New X509Certificate2("c:\works\gaimport\gaimport\Analyticsdata-xxxxxxxxxxxx.p12", _
"notasecret", X509KeyStorageFlags.Exportable)
Dim credential As New ServiceAccountCredential( _
New ServiceAccountCredential.Initializer(serviceAccountEmail) With { _
.Scopes = New String() {"https://www.googleapis.com/auth/analytics.readonly"} _
}.FromCertificate(certificate))
If credential.RequestAccessTokenAsync(CancellationToken.None).Result Then
Dim xoauthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)
Console.WriteLine("test" & xoauthKey)
End If
End Sub
End Class
Now I need somehing to get analytics part working. how do I use Those dll? Can I reguest feed from google (like i didi with clientId logins)?
I found a good traight forfard solution to my case (after getting acces token):
Dim webClient As New System.Net.WebClient
webClient.Encoding = System.Text.Encoding.UTF8
Dim requesturl = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A" & domainidid(domainrno) & "&start-date=" & viimekuunalkuset & "&end-date=" & viimekuunloppuset & "&metrics=ga%3Ausers%2Cga%3Asessions%2Cga%3Apageviews&access_token=" & credential.Token.AccessToken
Dim resultb As String = webClient.DownloadString(requesturl)
Then I just handeled JSON to get what I really wanted to get:
Dim myJ = JObject.Parse(resultb)
Dim totalsForAllResults = Convert.ToInt32(myJ("totalsForAllResults")("ga:sessions"))
Dim totalsForAllResultsusers = Convert.ToInt32(myJ("totalsForAllResults")("ga:users"))
Dim totalsForAllResultspgw = Convert.ToInt32(myJ("totalsForAllResults")("ga:pageviews"))

Uploading to Google drive using VBA?

I have an MS Access database which now requires me to 'attach' documents to it. My intention is to store the documents on Google Drive and have a link on the database for users to retrieve the documents.
As there are many users spread through different cities, it is not practical to require them to have synced Google Drive folders. All the users will need the ability to upload to the database/GD so my intention is to have a separate Google account for the database - with its own login details.
example:
User clicks button to upload file
Save as dialog box appears and user selects file
Database logs into its Google Drive and uploads selected file
Lots of problems with this though, the main one being that Google Drive does not support VBA.
If the user is logged into their own Gmail account, that will probably be another issue.
I came across this code for vb.net on another site.
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports Google.Apis.Services
Namespace GoogleDriveSamples
Class DriveCommandLineSample
Shared Sub Main(ByVal args As String)
Dim CLIENT_ID As [String] = "YOUR_CLIENT_ID"
Dim CLIENT_SECRET As [String] = "YOUR_CLIENT_SECRET"
'' Register the authenticator and create the service
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization)
Dim service = New DriveService(New BaseClientService.Initializer() With { _
.Authenticator = auth _
})
Dim body As New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("document.txt")
Dim stream As New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
Console.WriteLine("File id: " + file.Id)
Console.WriteLine("Press Enter to end this process.")
Console.ReadLine()
End Sub
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState( New () {DriveService.Scopes.Drive.GetStringValue()})
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Console.Write(" Authorization Code: ")
Dim authCode As String = Console.ReadLine()
Console.WriteLine()
' Retrieve the access token by using the authorization code:
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
End Namespace
It was suggested that the IE library could be utilised to log into the Google Drive and the API calls made from the above to upload. I don't know how to do this. Somewhere else it was mentioned that a 'COM wrapper' may be suitable. I don't have experience with any coding other than VBA (self taught) so am struggling to understand what the next step should be.
If anyone has done something similar or can offer any advice, I would be grateful to hear from you.
This thread might be dead now but if you are working with forms in your database and the user needs to be attaching the files to a particular record displayed in a form with a unique identification number then this is definitely possible but you would have to do it in an external application written in .NET I can provide you with the necessary code to get you started, vb.net is very similar to VBA.
What you would need to do is create a windows form project and add references to Microsoft access core dll and download the nugget package for google drive api from nugget.
Imports Google
Imports Google.Apis.Services
Imports Google.Apis.Drive.v2
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v2.Data
Imports System.Threading
Public Class GoogleDriveAuth
Public Shared Function GetAuthentication() As DriveService
Dim ClientIDString As String = "Your Client ID"
Dim ClientSecretString As String = "Your Client Secret"
Dim ApplicationNameString As String = "Your Application Name"
Dim secrets = New ClientSecrets()
secrets.ClientId = ClientIDString
secrets.ClientSecret = ClientSecretString
Dim scope = New List(Of String)
scope.Add(DriveService.Scope.Drive)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scope, "user", CancellationToken.None).Result()
Dim initializer = New BaseClientService.Initializer
initializer.HttpClientInitializer = credential
initializer.ApplicationName = ApplicationNameString
Dim Service = New DriveService(initializer)
Return Service
End Function
End Class
This code will authorise your drive service then you create a Public Shared Service As DriveService under your imports that can be used from any sub or function then call this function on your form load event like
Service = GoogleDriveAuth.GetAuthentication
Add a reference to your project to Microsoft Access 12.0 Object Library or whatever version you have
Then this piece of code will look at the form you want to get the value of the record no from and upload a file to your choice of folder
Private Sub UploadAttachments()
Dim NumberExtracted As String
Dim oAccess As Microsoft.Office.Interop.Access.Application = Nothing
Dim connectedToAccess As Boolean = False
Dim SelectedFolderIdent As String = "Your Upload Folder ID"
Dim CreatedFolderIdent As String
Dim tryToConnect As Boolean = True
Dim oForm As Microsoft.Office.Interop.Access.Form
Dim oCtls As Microsoft.Office.Interop.Access.Controls
Dim oCtl As Microsoft.Office.Interop.Access.Control
Dim sForm As String 'name of form to show
sForm = "Your Form Name"
Try
While tryToConnect
Try
' See if can connect to a running Access instance
oAccess = CType(Marshal.GetActiveObject("Access.Application"), Microsoft.Office.Interop.Access.Application)
connectedToAccess = True
Catch ex As Exception
Try
' If couldn't connect to running instance of Access try to start a running Access instance And get an updated version of the database
oAccess = CType(CreateObject("Access.Application"), Microsoft.Office.Interop.Access.Application)
oAccess.Visible = True
oAccess.OpenCurrentDatabase("Your Database Path", False)
connectedToAccess = True
Catch ex2 As Exception
Dim res As DialogResult = MessageBox.Show("COULD NOT CONNECT TO OR START THE DATABASE" & vbNewLine & ex2.Message, "Warning", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning)
If res = System.Windows.Forms.DialogResult.Abort Then
Exit Sub
End If
If res = System.Windows.Forms.DialogResult.Ignore Then
tryToConnect = False
End If
End Try
End Try
' We have connected successfully; stop trying
tryToConnect = False
End While
' Start a new instance of Access for Automation:
' Make sure Access is visible:
If Not oAccess.Visible Then oAccess.Visible = True
' For Each oForm In oAccess.Forms
' oAccess.DoCmd.Close(ObjectType:=Microsoft.Office.Interop.Access.AcObjectType.acForm, ObjectName:=oForm.Name, Save:=Microsoft.Office.Interop.Access.AcCloseSave.acSaveNo)
' Next
' If Not oForm Is Nothing Then
' System.Runtime.InteropServices.Marshal.ReleaseComObject(oForm)
' End If
' oForm = Nothing
' Select the form name in the database window and give focus
' to the database window:
' oAccess.DoCmd.SelectObject(ObjectType:=Microsoft.Office.Interop.Access.AcObjectType.acForm, ObjectName:=sForm, InDatabaseWindow:=True)
' Show the form:
' oAccess.DoCmd.OpenForm(FormName:=sForm, View:=Microsoft.Office.Interop.Access.AcFormView.acNormal)
' Use Controls collection to edit the form:
oForm = oAccess.Forms(sForm)
oCtls = oForm.Controls
oCtl = oCtls.Item("The Name Of The Control Where The Id Number Is On The Form")
oCtl.Enabled = True
' oCtl.SetFocus()
NumberExtracted = oCtl.Value
System.Runtime.InteropServices.Marshal.ReleaseComObject(oCtl)
oCtl = Nothing
' Hide the Database Window:
' oAccess.DoCmd.SelectObject(ObjectType:=Microsoft.Office.Interop.Access.AcObjectType.acForm, ObjectName:=sForm, InDatabaseWindow:=True)
' oAccess.RunCommand(Command:=Microsoft.Office.Interop.Access.AcCommand.acCmdWindowHide)
' Set focus back to the form:
' oForm.SetFocus()
' Release Controls and Form objects:
System.Runtime.InteropServices.Marshal.ReleaseComObject(oCtls)
oCtls = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(oForm)
oForm = Nothing
' Release Application object and allow Access to be closed by user:
If Not oAccess.UserControl Then oAccess.UserControl = True
System.Runtime.InteropServices.Marshal.ReleaseComObject(oAccess)
oAccess = Nothing
If NumberExtracted = Nothing Then
MsgBox("The Number Could Not Be Obtained From The Form" & vbNewLine & vbNewLine & "Please Ensure You Have The Form Open Before Trying To Upload")
Exit Sub
End If
If CheckForDuplicateFolder(SelectedFolderIdent, NumberExtracted + " - ATC") = True Then
CreatedFolderIdent = GetCreatedFolderID(NumberExtracted + " - ATC", SelectedFolderIdent)
DriveFilePickerUploader(CreatedFolderIdent)
Else
CreateNewDriveFolder(NumberExtracted + " - ATC", SelectedFolderIdent)
CreatedFolderIdent = GetCreatedFolderID(NumberExtracted + " - ATC", SelectedFolderIdent)
DriveFilePickerUploader(CreatedFolderIdent)
End If
Catch EX As Exception
MsgBox("The Number Could Not Be Obtained From The Form" & vbNewLine & vbNewLine & "Please Ensure You Have The Form Open Before Trying To Upload" & vbNewLine & vbNewLine & EX.Message)
Exit Sub
Finally
If Not oCtls Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(oCtls)
oCtls = Nothing
End If
If Not oForm Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(oForm)
oForm = Nothing
End If
If Not oAccess Is Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(oAccess)
oAccess = Nothing
End If
End Try
End
End Sub
Check For Duplicate Folders In The Destination Upload Folder
Public Function CheckForDuplicateFolder(ByVal FolderID As String, ByVal NewFolderNameToCheck As String) As Boolean
Dim ResultToReturn As Boolean = False
Try
Dim request = Service.Files.List()
Dim requeststring As String = ("'" & FolderID & "' in parents And mimeType='application/vnd.google-apps.folder' And trashed=false")
request.Q = requeststring
Dim FileList = request.Execute()
For Each File In FileList.Items
If File.Title = NewFolderNameToCheck Then
ResultToReturn = True
End If
Next
Catch EX As Exception
MsgBox("THERE HAS BEEN AN ERROR" & EX.Message)
End Try
Return ResultToReturn
End Function
Create New Drive Folder
Public Sub CreateNewDriveFolder(ByVal DirectoryName As String, ByVal ParentFolder As String)
Try
Dim body1 = New Google.Apis.Drive.v2.Data.File
body1.Title = DirectoryName
body1.Description = "Created By Automation"
body1.MimeType = "application/vnd.google-apps.folder"
body1.Parents = New List(Of ParentReference)() From {New ParentReference() With {.Id = ParentFolder}}
Dim file1 As Google.Apis.Drive.v2.Data.File = Service.Files.Insert(body1).Execute()
Catch EX As Exception
MsgBox("THERE HAS BEEN AN ERROR" & EX.Message)
End Try
End Sub
Get The Created Folder ID
Public Function GetCreatedFolderID(ByVal FolderName As String, ByVal FolderID As String) As String
Dim ParentFolder As String
Try
Dim request = Service.Files.List()
Dim requeststring As String = ("'" & FolderID & "' in parents And mimeType='application/vnd.google-apps.folder' And title='" & FolderName & "' And trashed=false")
request.Q = requeststring
Dim Parent = request.Execute()
ParentFolder = (Parent.Items(0).Id)
Catch EX As Exception
MsgBox("THERE HAS BEEN AN ERROR" & EX.Message)
End Try
Return ParentFolder
End Function
Drive File Picker Uploader To Upload Files Selected From A File Dialog Box To The Newly Created Folder
Public Sub DriveFilePickerUploader(ByVal ParentFolderID As String)
Try
ProgressBar1.Value = 0
Dim MimeTypeToUse As String
Dim dr As DialogResult = Me.OpenFileDialog1.ShowDialog()
If (dr = System.Windows.Forms.DialogResult.OK) Then
Dim file As String
Else : Exit Sub
End If
Dim i As Integer = 0
For Each file In OpenFileDialog1.FileNames
MimeTypeToUse = GetMimeType(file)
Dim filetitle As String = (OpenFileDialog1.SafeFileNames(i))
Dim body2 = New Google.Apis.Drive.v2.Data.File
body2.Title = filetitle
body2.Description = "J-T Auto File Uploader"
body2.MimeType = MimeTypeToUse
body2.Parents = New List(Of ParentReference)() From {New ParentReference() With {.Id = ParentFolderID}}
Dim byteArray = System.IO.File.ReadAllBytes(file)
Dim stream = New System.IO.MemoryStream(byteArray)
Dim request2 = Service.Files.Insert(body2, stream, MimeTypeToUse)
request2.Upload()
Next
Catch EX As Exception
MsgBox("THERE HAS BEEN AN ERROR" & EX.Message)
End Try
End Sub
Get The Mime Type Of The Files Being Uploaded
Public Shared Function GetMimeType(ByVal file As String) As String
Dim mime As String = Nothing
Dim MaxContent As Integer = CInt(New FileInfo(file).Length)
If MaxContent > 4096 Then
MaxContent = 4096
End If
Dim fs As New FileStream(file, FileMode.Open)
Dim buf(MaxContent) As Byte
fs.Read(buf, 0, MaxContent)
fs.Close()
Dim result As Integer = FindMimeFromData(IntPtr.Zero, file, buf, MaxContent, Nothing, 0, mime, 0)
Return mime
End Function
<DllImport("urlmon.dll", CharSet:=CharSet.Auto)> _
Private Shared Function FindMimeFromData( _
ByVal pBC As IntPtr, _
<MarshalAs(UnmanagedType.LPWStr)> _
ByVal pwzUrl As String, _
<MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.I1, SizeParamIndex:=3)> ByVal _
pBuffer As Byte(), _
ByVal cbSize As Integer, _
<MarshalAs(UnmanagedType.LPWStr)> _
ByVal pwzMimeProposed As String, _
ByVal dwMimeFlags As Integer, _
<MarshalAs(UnmanagedType.LPWStr)> _
ByRef ppwzMimeOut As String, _
ByVal dwReserved As Integer) As Integer
End Function
Hopefully this helps you make a start I am 100% convinced this is achievable as I have already done this for my manager.
This reply might be late but just wanna share one of the approach!
I have done this successfully with VBA and the demo link is here
http://www.sfdp.net/thuthuataccess/demo/democAuth.rar?attredirects=0&d=1
With this, you can upload, download or delete a file with your GoogleDrive in Access..
Just Wininet + WinHTTP enough
Dang Dinh ngoc
Vietnam

Importing Google Drive Quickstart Code to Visual Basic

I am trying to get the Quickstart code for .Net imported to Visual Basic (VB .NET) and I had some errors. I am a newbie to this kind of programming. Would appreciate some pointers, or someone pointing out something that is fundamentally wrong with the code.
Appreciate the help!
The errors that I get when I try to compile the Console App are:
Error 2 Argument not specified for parameter 'arg' of 'Private Shared Function GetAuthorization(arg As Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient) As DotNetOpenAuth.OAuth2.IAuthorizationState'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 22 86 Nipod Drive Console
Error 3 'BaseClientService' is ambiguous in the namespace 'Google.Apis.Services'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 23 48 Nipod Drive Console
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports Google.Apis.Services
Namespace GoogleDriveSamples
Class DriveCommandLineSample
Shared Sub Main(ByVal args As String)
Dim CLIENT_ID As [String] = "YOUR_CLIENT_ID"
Dim CLIENT_SECRET As [String] = "YOUR_CLIENT_SECRET"
'' Register the authenticator and create the service
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization)
Dim service = New DriveService(New BaseClientService.Initializer() With { _
.Authenticator = auth _
})
Dim body As New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("document.txt")
Dim stream As New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
Console.WriteLine("File id: " + file.Id)
Console.WriteLine("Press Enter to end this process.")
Console.ReadLine()
End Sub
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState( New () {DriveService.Scopes.Drive.GetStringValue()})
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Console.Write(" Authorization Code: ")
Dim authCode As String = Console.ReadLine()
Console.WriteLine()
' Retrieve the access token by using the authorization code:
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
End Namespace
I reliase this is an old subject, but this may help someone in future, make sure you compile in framework 3.5
Sorry cant seem to edit or delete my previous answer, for anyone in future, this should help:
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports System.Security
Imports Google.Apis.Services
Public Class GoogleDrive
Public Function UploadFile() As Boolean
Const CLIENT_ID As String = "xxxxxxxxxxxxx.apps.googleusercontent.com"
Const CLIENT_SECRET As String = "-yyyyyyyyyyyyyyyyyyyyyyy"
'Register the authenticator and create the service
Dim provider As NativeApplicationClient = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim getAuth As Func(Of NativeApplicationClient, IAuthorizationState) = AddressOf GetAuthorization
Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, getAuth)
Dim service = New DriveService(New BaseClientService.Initializer() With {.Authenticator = auth})
Dim body As File = New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("D:\document.txt")
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
MessageBox.Show("File : " & file.Id)
End Function
Private Function GetAuthorization(ByVal Client As NativeApplicationClient) As IAuthorizationState
Dim RetVal As IAuthorizationState
Dim state As IAuthorizationState = New AuthorizationState(New String() {DriveService.Scopes.Drive.GetStringValue()})
'Check to see if we have a saved refresh token
If My.Settings.SavedAuth.ToString <> "" Then
state.RefreshToken = My.Settings.SavedAuth
If (Client.RefreshToken(state)) Then
Return state
End If
End If
'Get the auth URL:
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = Client.RequestUserAuthorization(state)
'Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
'wait until user has entered the code
Dim authCode As String = InputBox("Authorisation code", "Authorisation Code", "")
'Retrieve the access token by using the authorization code:
RetVal = Client.ProcessUserAuthorization(authCode, state)
'store the refresh token
Call StoreRefreshToken(state.RefreshToken)
Return RetVal
End Function
Private Function LoadRefreshToken() As String
Return My.Settings.SavedAuth
End Function
Private Sub StoreRefreshToken(ByVal Token As String)
My.Settings("SavedAuth") = Token
My.Settings.Save()
End Sub
End Class