VB Net: How to call this Public Shared Function? - vb.net

Can anybody help me with a couple of doubts?
How can I call this Public Shared Function from a button? and how can I show "result" (list of files) in a datagridview?
Thanks.
Imports System.Threading
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'?
End Sub
Public Shared Function retrieveAllFiles(service As DriveService) As List(Of File)
Dim Secrets = New ClientSecrets()
Secrets.ClientId = "CLIENT ID"
Secrets.ClientSecret = "CLIENT SECRET"
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 = "APPLICATION NAME"
Dim service = New DriveService(initializer)
Dim request As FilesResource.ListRequest = service.Files.List()
Dim result As New List(Of File)()
Dim request As FilesResource.ListRequest = service.Files.List()
Do
Try
Dim files As FileList = request.Execute()
result.AddRange(files.Items)
request.PageToken = files.NextPageToken
Catch e As Exception
Console.WriteLine("An error occurred: " + e.Message)
request.PageToken = Nothing
End Try
Loop While Not [String].IsNullOrEmpty(request.PageToken)
Return result
End Function
End Class

If it's in the same class, you can just call it by name, same as a non-shared function:
lst = retrieveAllFiles(service)
If it's in another class, you need to prefix it with class name:
lst = className.retrieveAllFiles(service)
Official reference:
Shared Members in Visual Basic

Related

VB.NET Tool To List And Change Users Groups On Active Directory

I'm trying to make a tool to list and change users group on active directory based on groups that manager has control. I'm stuck on listing function, and it keep getting me this error:
System.DirectoryServices.DirectoryServicesCOMException
Hresult=0x80072032 Message=Invalid distinguished name (DN) syntax specified
Line: Dim searchResults As Search...
Public Class Form1
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
Dim managerID As String
managerID = mngID.Text
Dim employeeID As String
employeeID = empID.Text
Dim emptybox
emptybox = mngID.Text.Length
If emptybox < 8 Then
MsgBox("ManagerID Inválido")
End If
Dim emptybox2
emptybox2 = empID.Text.Length
If emptybox2 < 8 Then
MsgBox("EmployeeID Inválido")
End If
If emptybox = 8 Then
Dim domain = New PrincipalContext(ContextType.Domain)
Dim user = UserPrincipal.FindByIdentity(domain, managerID)
Dim userDN
userDN = user.DistinguishedName
Dim ADEntry As New DirectoryEntry
ADEntry.Path = "LDAP://domain/CN:Users;DC:domain"
Dim Groups As New Collection
Dim mySearcher As DirectorySearcher = New DirectorySearcher(ADEntry)
Dim arrList As New ArrayList()
mySearcher.Filter = "(&(ObjectClass=user)(DistinguisedName=" & userDN & "))"
mySearcher.PropertiesToLoad.Add("MemberOf")
Dim searchResults As SearchResultCollection = mySearcher.FindAll()
If searchResults.Count = 0 Then
MsgBox("ManagerID inválido2")
End If
If searchResults.Count > 0 Then
Dim group As New DirectoryEntry(searchResults(0).Path)
For Each member As Object In group.Properties("MemberOf")
groupbox.Items.Add(member)
Next
End If
End If
End Sub
Your Error
Error 0x80072032 - ERROR_DS_INVALID_DN_SYNTAX
An invalid 'dn' syntax has been specified
Here's something to get you going.
Example VB Script To Connect to Active Directory
Imports System
Imports System.Data
Imports System.Linq
Imports System.IO
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Imports System.Security
Imports System.Security.Permissions
Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Public Function EnumerateDomains() As ArrayList
Dim alDomains As New ArrayList()
Dim currentForrest As Forest = Forest.GetCurrentForest()
Dim myDomains As DomainCollection = currentForrest.Domains
For Each objDomain As Domain In myDomains
alDomains.Add(objDomain.Name)
Next
Return alDomains
End Function
Public Function EumerateDomainUsers() As ArrayList
Dim domainUsers As New ArrayList()
Dim usr As String
'Dim fqdns As String = DropDownList1.SelectedItem.ToString()
Dim fqdns As String = DropDownList1.SelectedItem.Text
Dim adStrng As String = "LDAP://" & fqdns
Dim adEntry As DirectoryEntry = GetObject(adStrng)
Dim searcher As DirectorySearcher = New DirectorySearcher(adEntry)
searcher.Sort.PropertyName = "cn"
Dim results As SearchResultCollection
Dim result As SearchResult
searcher.PropertiesToLoad.Add("cn")
results = searcher.FindAll
For Each result In results
usr = result.GetDirectoryEntry().Properties("cn").Value
domainUsers.Add(usr)
Next
Return domainUsers
End Function
There is a spelling mistake and should be "DistinguishedName" instead of "DistinguisedName":
mySearcher.Filter = "(&(ObjectClass=user)(DistinguishedName=" & userDN & "))"

vb.net 2017 unable to insert Calendar event

I have looked at all the examples I could find and hobbled together the code below. The first time I ran it a web page asked if I wanted to allow my user to update Google calendar and then it asked me to select an account. After that it just sat there and my windows application never finished painting the screen and displaying the simple button I had placed on a form from which to run the insert calendar event. Now when I run the code it comes up, a small gray window appears and it just sits there. What am I doing wrong?
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports Google.Apis.Calendar.v3
Imports Google.Apis.Calendar.v3.Data
Imports Google.Apis.Calendar.v3.EventsResource
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Util.Store
Imports Google.Apis.Requests
Public Class Form1
Dim service As CalendarService
Dim GRPS As IList(Of String) = New List(Of String)()
Sub New()
Authenticate()
End Sub
Private Function Authenticate()
GRPS.Add(CalendarService.Scope.Calendar)
Dim credential As UserCredential
Using stream As New FileStream("client_secret.json", FileMode.Open,
FileAccess.Read)
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, GRPS, "user",
CancellationToken.None, New
FileDataStore("Vanguard")).Result
End Using
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer()
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "Vanguard"
service = New CalendarService(initializer)
Return 0
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
InsertCalendar()
MessageBox.Show("Done")
Application.Exit()
End Sub
Public Sub InsertCalendar()
Dim CalendarEvent As New Data.Event
Dim SDT As New Data.EventDateTime
Dim A As Date = DateSerial(2017, 8, 11)
A = A.AddHours(10)
A = A.AddMinutes(30)
SDT.DateTime = A
Dim b As Date
b = A.AddHours(2)
Dim EDT As New Data.EventDateTime
EDT.DateTime = b
CalendarEvent.Start = SDT
CalendarEvent.End = EDT
CalendarEvent.Id = System.Guid.NewGuid.ToString
CalendarEvent.Description = "Test Event"
Dim list As IList(Of CalendarListEntry) =
service.CalendarList.List().Execute().Items()
service.Events.Insert(CalendarEvent, list(0).Id).Execute()
End Sub
End Class

VB.NET [Cross-thread operation not valid: Control 'txtIncomingText' accessed from a thread........]

I'm a beginner in VB.NET, please bear with me.
I've downloaded a multiclient TCP-IP Socket Server-Client application in VB.NET. The Server listens pretty well, but the Client encounters below exception:
"Cross-thread operation not valid: Control 'txtIncomingText' accessed from a thread other than the thread it was created on."
I'll be greateful if you guys could help me with corrected version of the code. Thank you.
' ------- CLIENT CODE -------
Imports System.Windows.Forms
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Public Class frmClient
Inherits Form
Private Sub frmClient_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private _clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Public Sub New()
InitializeComponent()
End Sub
Private receivedBuf As Byte() = New Byte(1023) {}
Private thr As Thread
Private Sub ReceiveData(ar As IAsyncResult)
Dim socket As Socket = DirectCast(ar.AsyncState, Socket)
Dim received As Integer = socket.EndReceive(ar)
Dim dataBuf As Byte() = New Byte(received - 1) {}
Array.Copy(receivedBuf, dataBuf, received)
' These two lines encounter an error ->>>>>
txtIncomingText.Text = (Encoding.ASCII.GetString(dataBuf))
rbChat.Text = "\nServer: " + txtIncomingText.Text
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), _clientSocket)
End Sub
Private Sub SendLoop()
While True
'Console.WriteLine("Enter a request: ");
'string req = Console.ReadLine();
'byte[] buffer = Encoding.ASCII.GetBytes(req);
'_clientSocket.Send(buffer);
Dim receivedBuf As Byte() = New Byte(1023) {}
Dim rev As Integer = _clientSocket.Receive(receivedBuf)
If rev <> 0 Then
Dim data As Byte() = New Byte(rev - 1) {}
Array.Copy(receivedBuf, data, rev)
lbStt.Text = ("Received: " + Encoding.ASCII.GetString(data))
rbChat.AppendText(vbLf & "Server: " + Encoding.ASCII.GetString(data))
Else
_clientSocket.Close()
End If
End While
End Sub
Private Sub LoopConnect()
Dim attempts As Integer = 0
While Not _clientSocket.Connected
Try
attempts += 1
_clientSocket.Connect(IPAddress.Loopback, 420)
Catch generatedExceptionName As SocketException
'Console.Clear();
lbStt.Text = ("Connection attempts: " + attempts.ToString())
End Try
End While
lbStt.Text = ("Connected!")
End Sub
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
If _clientSocket.Connected Then
Dim buffer As Byte() = Encoding.ASCII.GetBytes(txtText.Text)
_clientSocket.Send(buffer)
rbChat.AppendText("Client: " + txtText.Text)
End If
End Sub
Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
LoopConnect()
' SendLoop();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), _clientSocket) Dim buffer As Byte() = Encoding.ASCII.GetBytes("##" + txtName.Text)
_clientSocket.Send(buffer)
End Sub
End Class
Well, you should invoke the calls on the control's thread. This is a quick and dirty solution
Dim message = Encoding.ASCII.GetString(dataBuf)
txtIncomingText.Invoke(Sub() txtIncomingText.Text = message)
rbChat.Invoke(Sub() rbChat.Text = Environment.NewLine & "Server: " & message)
But you should check if invocation is required first. See https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx
Also, "\n" is not how you make a new line in vb.net (did you copy this code from c#?).
And + is not how you concatenate strings in vb.net (see above parenthesis).

Error 401 with Google contacts API on VB Net

I made today a vb net application to fetch my contacts and it was working for one hour then when I try to use my app I get this error:
This is the code I´m using:
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports Google.Contacts
Imports Google.GData.Contacts
Imports Google.GData.Client
Imports Google.GData.Extensions
Public Class Form1
Dim initializer = New BaseClientService.Initializer
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Secrets = New ClientSecrets()
Secrets.ClientId = "MYCLIENTID"
Secrets.ClientSecret = "MYCLIENTSECRET"
Dim scopes As String() = New String() {"https://www.googleapis.com/auth/contacts.readonly"}
Try
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scopes, "email#email.com", CancellationToken.None, New FileDataStore("MYAPPNAME")).Result()
Dim parameters As New OAuth2Parameters()
parameters.AccessToken = credential.Token.AccessToken
parameters.RefreshToken = credential.Token.RefreshToken
Dim settings As New RequestSettings("MYAPPNAME", parameters)
Dim cr As New ContactsRequest(settings)
Dim f As Feed(Of Contact) = cr.GetContacts()
For Each c As Contact In f.Entries
MsgBox(c.Name.FullName)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
How can I solve this issue?
Why this is happening after a good performance?
Thanks
I solved it changing the form of this line:
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scopes,"email#email.com", CancellationToken.None, New FileDataStore("MYAPPNAME")).Result()
by this lines:
Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {
.ClientId = "MYCLIENTID",
.ClientSecret = "MYCLIENTSECRET"
}, scopes, "email#gmail.com", CancellationToken.None, New FileDataStore("MYAPPNAME")).Result
And taking out the secrets section.
Thank you all for your advices.

How can I get the events for one day (Google calendar Api) using TimeMax and TimeMin in net?

I have a code for get a event list of calendar but retrieves ALL events. How can I get the events for just ONE day?
Here is the code that Im using:
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports System.Collections.Generic
Imports Google.Apis.Calendar.v3
Imports Google.Apis.Calendar.v3.Data
Imports Google.Apis.Calendar.v3.Data.Event
Imports Google.Apis.Util.Store
Imports Google.Apis.Calendar.v3.EventsResource
Imports System.Threading
Public Class Form1
Dim scopes As IList(Of String) = New List(Of String)
Dim service As CalendarService
Dim initializer = New BaseClientService.Initializer
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
Dim service As CalendarService
Try
scopes.Add(CalendarService.Scope.Calendar)
Dim Secrets = New ClientSecrets()
Secrets.ClientId = "CLIENT ID"
Secrets.ClientSecret = "CLIENT SECRET"
Dim scope = New List(Of String)
scope.Add(CalendarService.Scope.Calendar)
Dim credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, scopes, "xxxxxxxxxxx#developer.gserviceaccount.com", CancellationToken.None).Result()
Dim initializer = New BaseClientService.Initializer
initializer.HttpClientInitializer = credential
initializer.ApplicationName = "APP NAME"
service = New CalendarService(initializer)
Dim list As IList(Of CalendarListEntry) = service.CalendarList.List().Execute().Items
Dim requeust As ListRequest = service.Events.List("MY EMAIL")
Me.DataGridView1.DataSource = requeust.Execute.Items
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Try to add your searching range with these few lines of code
requeust.TimeMax = Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")
requeust.TimeMin = "2014-12-01T16:00:00" 'changing the time whenever you want
I think it's work :)