I am using the following code to connect to Google Calendar 3.
Dim datafolder As String = Server.MapPath("App_Data/CalendarService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = "101935195xxxxxx-jm6o24ifgbixxxxxxxxxxxx#developer.gserviceaccount.com".Trim()
scopes.Add("https://www.googleapis.com/auth/calendar")
Dim myclientsecret As New ClientSecrets() With { _
.ClientId = myClientID, _ ' It is saved in the web config
.ClientSecret = ClientSecret _ ' It is saved in the web config
}
Dim flow As GoogleAuthorizationCodeFlow
Try
flow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With { _
.DataStore = New FileDataStore(datafolder), _
.ClientSecrets = myclientsecret, _
.Scopes = scopes
})
Catch ex As Exception
lblerr.Text = ex.ToString
End Try
It throws:
System.TypeInitializationException: The type initializer for 'Google.Apis.Http.ConfigurableMessageHandler' threw an exception.
System.IO.FileLoadException: Could not load file or assembly 'System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
What am I doing wrong with this coding? Why am I not getting authenticated?
I have seen a similar error when using external libraries (e.g. DLL's) which are downloaded from the internet. Your post doesn't mention this, but I'll post here just in case this applies to you.
Make sure any external libraries used by your project are not blocked by Windows. You can do this by right-clicking the library file (e.g. the DLL) and going to Properties. At the bottom, if this applies, there will be a button to "Unblock". Click it and then try to run your project again.
Additional info and automation options can be found here: http://www.howtogeek.com/70012/what-causes-the-file-downloaded-from-the-internet-warning-and-how-can-i-easily-remove-it/
Related
I am currently working on a REST API to be able to call a WCF service via it. Now I have the problem when I try to call up tasks via Azure DevOps using this method,
<OperationContract()>
<WebGet(UriTemplate:="/todos?user={sUser}&projectID={lProjektID}", BodyStyle:=WebMessageBodyStyle.Wrapped, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function GetTodos(Optional ByVal sUser As String = "%", Optional ByVal lProjektID As Long = Nothing) As List(Of ProjektToDo)
I get these exceptions after trying to connect to Azure Devops at this:
Dim creds As New VssBasicCredential(String.Empty, _DevOpsPAT)
Dim connection As VssConnection = New VssConnection(New Uri(My.Settings.TFSBasisUrlSSL), creds)
'Create instance of WorkItemTrackingHttpClient using VssConnection
Dim witClient As WorkItemTrackingHttpClient = connection.GetClient(Of WorkItemTrackingHttpClient) 'This connection fails !'
Dim queryHierarchyItems As List(Of QueryHierarchyItem) = witClient.GetQueriesAsync(Projekt,, 2).Result
"System.Net.Sockets.SocketException" in System.dll
"System.IO.IOException" in System.dll
"System.ObjectDisposedException" in System.dll
"System.Net.WebException" in System.dll
"System.Net.Http.HttpRequestException" in Microsoft.VisualStudio.Services.Common.dll
"System.Net.Http.HttpRequestException" in mscorlib.dll.
The InnerException of the ex.Message tells me "An existing connection was closed by the remote host" Message: "Unable to read data from the transfer connection".
I'm currently training in a new company and have no experience in the area of Rest API and WCF Service, please help me I'm desperate about this task because I just don't know where to start.
due to our applications being moved onto a Citrix VM platform I need to move our application settings config files from C:\ProgramData to an alternative location. With this particular application each user has their own config file, which is effectively a clone of the app.config file but with just user specific content, for example encrypted authentication credentials.
With this in mind, I modified the code to save the config files to a mapped network drive. Using system.configuration I am able to read content without any issues from the networked drive but when I attempt to write changes I get the following error message:
*"Attempted to perform an unauthorized operation."
The following is the function which generates the error:
Public Shared Function WriteSettingUser(ByVal configPath As String, ByVal userName As String, ByVal sectionName As String, ByVal setting As String, ByVal value As String) As String
Dim result As Boolean = False
Dim filemap As New ExeConfigurationFileMap
Dim config As Configuration
Dim section As AppSettingsSection
Try
filemap.ExeConfigFilename = configPath & userName & ".config"
config = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None)
section = config.GetSection(sectionName)
section.Settings(setting).Value = value
config.Save()
result = True
Catch ex As Exception
Throw
result = False
Finally
End Try
Return result
The error is generated at the 'config.save' line.
Would appreciate any insight into this issue.
Kind Regards
Paul J.
I've been trying to follow https://developers.google.com/drive/v3/web/quickstart/dotnet and the Google API documentation, as well as searching all over the internet, but there really isn't a straightforward example to use (especially for v3)
I have a VB.NET GUI that contains a listview with the names of all plain text files in a folder. Clicking on one will display its' contents in a textbox. You can also type into a blank text box and save it. I want to allow multiple users to upload their text file to the Google Drive and be able to download all text files that are stored there.
I don't have much of an issue translating code from C# to VB.NET, and I think I'm fine with authenticating the service account with Google (or at least I don't get an error), but uploading only shows me response = Nothing. Any help is appreciated.
I created the service account through Google and have the following:
Dim service = AuthenticateServiceAccount("xxxxx#xxxxx.iam.gserviceaccount.com", "C:\Users\xxxxx\Documents\Visual Studio 2015\Projects\MyProject\accountkey-0c1aa839896b.json")
If drive.UploadFile(service, "C:\Users\xxxxx\Documents\Visual Studio 2015\Projects\MyProject\file.txt") Is Nothing Then
MsgBox("File not uploaded")
Else
MsgBox("File uploaded")
End If
Authenticate:
Public Function AuthenticateServiceAccount(ByVal serviceAccountEmail As String, ByVal serviceAccountCredentialFilePath As String) As DriveService
Dim scopes As String() = {DriveService.Scope.Drive, DriveService.Scope.DriveAppdata, DriveService.Scope.DriveReadonly, DriveService.Scope.DriveFile, DriveService.Scope.DriveMetadataReadonly, DriveService.Scope.DriveReadonly, DriveService.Scope.DriveScripts}
Try
If (String.IsNullOrEmpty(serviceAccountCredentialFilePath)) Then
Throw New Exception("Path to the service account credentials file is required.")
End If
If Not IO.File.Exists(serviceAccountCredentialFilePath) Then
Throw New Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath)
End If
If (String.IsNullOrEmpty(serviceAccountEmail)) Then
Throw New Exception("ServiceAccountEmail is required.")
End If
If (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() = ".json") Then
Dim credential As GoogleCredential
Dim sstream As New FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read)
credential = GoogleCredential.FromStream(sstream)
credential.CreateScoped(scopes)
'Create the Analytics service.
Return New DriveService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "Drive Service Account Authentication Sample"
})
Else
Throw New Exception("Unsupported Service accounts credentials.")
End If
Catch e As Exception
MsgBox("Create service account DriveService failed" + e.Message)
Throw New Exception("CreateServiceAccountDriveFailed", e)
End Try
End Function
Upload File:
Public Function UploadFile(service As DriveService, FilePath As String) As Google.Apis.Drive.v3.Data.File
If (System.IO.File.Exists(FilePath)) Then
Dim body As New Google.Apis.Drive.v3.Data.File()
body.Name = System.IO.Path.GetFileName(FilePath)
body.Description = "Text file"
body.MimeType = "text/plain"
'files content
Dim byteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim stream As New System.IO.MemoryStream(byteArray)
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, "text/plain")
request.Upload()
Return request.ResponseBody
Catch e As Exception
MsgBox("An error occurred: " + e.Message)
Return Nothing
End Try
Else
MsgBox("File does not exist: " + FilePath)
Return Nothing
End If
End Function
As stated here, since you are using a Service Account, all the folders and files will be created in this Service Account's Drive which cannot be accessed through a web UI and will be limited to the default quota.
To add content in a user's Drive, you will need to go through the regular OAuth 2.0 flow to retrieve credentials from this user. You can find more information about OAuth 2.0 on this pages:
Retrieve and use OAuth 2.0 credentials.
Quickstart: it has a quickstart sample in C# that you could use.
Using OAuth 2.0 to access Google APIs
You may also check this related thread: upload files to Google drive in VB.NET - searching for working code
I'm trying to upload a file to dropbox. The file gets uploaded and code works when i'm running locally. But file never gets uploaded when published on the server. I'm having the following error .
Could not load type 'System.Security.Authentication.SslProtocols' from assembly 'System.Net.Primitives, Version=4.0.0.0, Culture=neutral, PublicKeyToken=*********'.
I'm trying the below code sample to upload it
public sub uploadtodropbox()
Using httpclient As New HttpClient
httpclient.Timeout = TimeSpan.FromMinutes(20)
Dim _DropboxClient = New DropboxClient(ApiKeyDropBox, config)
Dim resultstring As String = UploadToDB(_DropboxClient, dropboxdir, docName, fileBytes)
_DropboxClient.Dispose()
If Not resultstring = "RanToCompletion" Then
ErrorMsg &= "The following error occured: " & resultstring
End If
End Using
End Sub
and this is the funtion that is uploading to Dropbox
Private Function UploadToDB(_DropboxClient As DropboxClient, Directory As String, Filename As String, Content As [Byte]()) As String
Try
Dim result As String = "Unknown"
Dim trycnt As String = 0
Dim tryLimit As String = 20
Dim respnse As Task(Of FileMetadata)
Using _mStream = New MemoryStream(Content)
respnse = _DropboxClient.Files.UploadAsync(Convert.ToString(Directory & Convert.ToString("/")) & Filename, WriteMode.Overwrite.Instance, body:=_mStream)
While Not respnse.IsCompleted And trycnt < tryLimit
Threading.Thread.Sleep(1000)
trycnt += 1
result = respnse.Status.ToString()
End While
UploadToDB = result
End Using
End try
END function.
I have tried without using the httpclient then i am getting this error :
The type initializer for 'Dropbox.Api.DropboxRequestHandlerOptions' threw an exception.
Thank you
I go the answer . I have system.Net.primitives assembly that is creating a problem uploading the file to Dropbox. All i need to do is delete the reference and also the System.Net.Http has versions have been set wrong in the web.config file. Once i set that in the configuration everything works fine.
For the certificate I have set the on post back to validate and allow the certificates generated in the event handler.
I have tried a diverse amount of methods this is my latest method which I have tried to not fire the error but to no avail I still get the FileIOPermission error
The Full error is
Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed
The code I am using is the below
Dim permissions As New Security.PermissionSet(Security.Permissions.PermissionState.None)
permissions.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted))
permissions.AddPermission(New Security.Permissions.SecurityPermission(Security.Permissions.SecurityPermissionFlag.Execution))
permissions.AddPermission(New Security.Permissions.SecurityPermission(Security.Permissions.SecurityPermissionFlag.Assertion))
permissions.Assert()
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions)
Dim asm As Reflection.Assembly = Reflection.Assembly.Load("ReportingServiceUtils, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cca1b177d76f2036")
Dim asm_name As Reflection.AssemblyName = asm.GetName()
ReportViewer1.LocalReport.AddFullTrustModuleInSandboxAppDomain(New Security.Policy.StrongName(New Security.Permissions.StrongNamePublicKeyBlob(asm_name.GetPublicKeyToken()), asm_name.Name, asm_name.Version))
The Code being used in the dll is the below
Public Sub Add(ByVal group As String, ByVal groupCurrentPageNumber As String)
Try
If _GroupWithRunningMaxPageNumber.ContainsKey(group) Then
_GroupWithRunningMaxPageNumber(group) = groupCurrentPageNumber
Else
If _GroupWithRunningMaxPageNumber.Count = 0 Then
Dim fileName = "C:\Working Folder\ms-dot-net-report-viewer-group-pagenation\ReportingServiceUtils\test.xml"
sw = New System.IO.StreamWriter(fileName, False)
sw.WriteLine("<root>")
sw.WriteLine("</root>")
sw.Close()
sw.Dispose()
End If
_GroupWithRunningMaxPageNumber.Add(group, groupCurrentPageNumber)
sw.WriteLine("<Group current='" & group & "' lastPage='" & CStr(groupCurrentPageNumber) & "'/>", 1, 1)
sw.Close()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Does anyone see anything wrong with the below code
I have found the solution and it was quite funny when I did.
The below 1 liner solves the problem of not being able to have file access from report.
Dim auth As New System.Security.Permissions.FileIOPermission( System.Security.Permissions.PermissionState.Unrestricted)
Using PermissionSet
var sec = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(sec);
You can convert from C# to VB.net easyly