Exception : There is no such object on the server at System - vb.net

I try to obtain a certificate with LDAP, but i have an exception
System.Runtime.InteropServices.COMException(0x80072030): There is no such object on the server at System
My code :
Dim ldapUrl = "LDAP://annuaire.sesam-vitale.fr/cn=amo_pj.test#test.rss.fr,ou=AC-FACTURATION,ou=AC-SESAM-VITALE-2034,o=sesam-vitale,c=fr?userCertificate;binary"
Dim de As DirectoryEntry = New DirectoryEntry(ldapUrl)
de.AuthenticationType = AuthenticationTypes.None
Dim dsearch As DirectorySearcher = New DirectorySearcher(de)
dsearch.Filter = "(objectClass=*)"
Dim rs As SearchResult = dsearch.FindOne()
I have this exception at last line. I have no idea and need your help.
Thank you
(sorry for my english)
EDIT
I resolve my problem :
Public Function certificatLDAP() As X509Certificate2
Dim certificat As X509Certificate2 = Nothing
Dim ldapconn As LdapConnection = New LdapConnection(New LdapDirectoryIdentifier("annuaire.sesam-vitale.fr"))
Try
ldapconn.AuthType = AuthType.Anonymous
ldapconn.SessionOptions.ProtocolVersion = 3
Dim attribut(1) As String
attribut(0) = "userCertificate;binary"
Dim request As SearchRequest = New SearchRequest("cn=amo_pj.test#test.rss.fr,ou=AC-FACTURATION,ou=AC-SESAM-VITALE-2034,o=sesam-vitale,c=fr", "(ObjectClass=*)", Protocols.SearchScope.Base, attribut)
Dim reponse As SearchResponse = CType(ldapconn.SendRequest(request), SearchResponse)
For Each test As SearchResultEntry In reponse.Entries
For Each toto As DictionaryEntry In test.Attributes
Dim tata As DirectoryAttribute = toto.Value
Dim tutu As Byte() = tata(0)
Return New X509Certificate2(tutu)
Next
Next
Catch ex As Exception
Throw ex
Finally
ldapconn.Dispose()
End Try
Return certificat
End Function

Related

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

BatchUpdate Rows in Google Sheets using VB.Net

Im having trouble updating rows in Google Sheets using VB.Net.
This is my code:
Dim service = New SheetsService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential, .ApplicationName = ApplicationName})
Dim spreadsheetId As String = "1mW-ndDolz_uECCMmAmKZ-sANoM9H53eqc231g98I06U"
Dim spreadsheet As Spreadsheet = Nothing
Dim content As BatchUpdateSpreadsheetRequest = New BatchUpdateSpreadsheetRequest()
Dim request As Request = New Request()
Dim deleteDimensionRequest As DeleteDimensionRequest = New DeleteDimensionRequest()
Dim dimensionRange As DimensionRange = New DimensionRange()
dimensionRange.Dimension = "A:B"
dimensionRange.StartIndex = 0
dimensionRange.EndIndex = 3
dimensionRange.SheetId = 0
deleteDimensionRequest.Range = dimensionRange
Dim requests As IList(Of Object) = New List(Of Object)()
requests.Add(request)
content.Requests = requests
Try
service.Spreadsheets.BatchUpdate(content, spreadsheetId)
Catch e As IOException
MsgBox(e.Message)
End Try
It shows me an Error saying
Unable to cast object of type
'System.Collections.Generic.List1[System.Object]' to type
'System.Collections.Generic.IList1[Google.Apis.Sheets.v4.Data.Request]'.
What Am I doing wrong here?
I have no idea how VB.NET works, but based on your sample code and the error message, I would assume the problem is this line:
Dim requests As IList(Of Object) = New List(Of Object)()
It should probably be:
Dim requests As IList(Of Request) = New List(Of Request)()
I am sure its working but I don't know its drawbacks
Dim requests As IList(Of Request)
dim Req1 as List(Of Request) = new List(Of Request)
Req1.Add(request)
Requests = Req1.ToList()
content.Requests = requests

Adding a dynamic member to an ExpandoObject

In the following method I am trying to add a dynamic member to an expando object but it throws an exception:
public member not found for expand object
Private Sub GetAckValues()
Try
Dim ack_duration As String = String.Empty
Dim ack_by_user_fkid As String = String.Empty
Dim ack_time As String = String.Empty
ack_duration = txtdefaultack.Text
ack_by_user_fkid = Convert.ToString(Session("user_code"))
Dim Ack_Detail As Object = New ExpandoObject()
Ack_Detail.ack_duration = ack_duration
Ack_Detail.ack_by_user_fkid = ack_by_user_fkid
receiptObject.StatusObject = Ack_Detail
Catch ex As Exception
logger.Error("Enter JobRequest form done by :" & LoggedinUserId, ex)
End Try
End Sub
Should this:
Ack_Detail.ack_duration = Ack_Detail.ack_duration
actually be this:
Ack_Detail.ack_duration = ack_duration

Can't get attributes from AD using vb.net

I use below code to get first name, last name, email, and department from AD using VB.Net 1.1
Public Shared Function GetAttribute(ByVal username As String, ByVal pwd As String) As UserInfo
Dim objUserInfo As New UserInfo
Dim ObjFirstName As String = ""
Dim ObjLastName As String = String.Empty
Dim ObjEmail As String = ""
Dim objDepartment As String = ""
Dim Success As Boolean = False
Dim LDAPAddress As String = ConfigurationSettings.AppSettings.Get("LDAPAddress")
Dim Entry As New System.DirectoryServices.DirectoryEntry(LDAPAddress, username, pwd)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
Dim Filter As String = "(samAccountName=" & username & ")"
Dim findUser As DirectorySearcher = New DirectorySearcher(Entry, Filter)
Dim results As SearchResultCollection = findUser.FindAll
Try
Dim Resultsx As System.DirectoryServices.SearchResult = Searcher.FindOne
Success = Not (Resultsx Is Nothing)
findUser.PropertiesToLoad.Add("name")
Dim name As String = DirectCast(Resultsx.Properties(name)(0), String)
Dim de As System.DirectoryServices.DirectoryEntry = Resultsx.GetDirectoryEntry()
Dim gg = de.Properties.PropertyNames()
For Each Onn As String In gg
Dim str As String = String.Format("{0}", Onn)
Next
Try
ObjFirstName = de.Properties("GivenName").Value.ToString()
ObjEmail = de.Properties("mail").Value.ToString()
ObjLastName = de.Properties("sn").Value.ToString()
objDepartment = de.Properties("department").Value.ToString()
Catch ex As Exception
ObjFirstName = de.Properties("DisplayName").Value.ToString()
End Try
But I can't get those attributes. in
Dim str As String = String.Format("{0}", Onn)
there are only 15 attributes, and there are no firstname, lastname, email, and department. What am I doing wrong?
Your code, though old-fashioned, looks fine on first sight. If you insist to continue with your code, I'll have a look later.
In the meantime, this code should fit your situation:
Dim user As DirectoryEntry = New DirectoryEntry("UserDN")
Dim src As DirectorySearcher = New DirectorySearcher(user, "(&(objectClass=user)(objectCategory=Person))")
src.PropertiesToLoad.Add("sn")
src.PropertiesToLoad.Add("givenName")
src.PropertiesToLoad.Add("mail")
src.PropertiesToLoad.Add("department")
Dim res As SearchResult = src.FindOne
Console.WriteLine(res.Properties("sn")(0))
Console.WriteLine(res.Properties("givenName")(0))
Console.WriteLine(res.Properties("mail")(0))
Console.WriteLine(res.Properties("department")(0))
Console.ReadLine()

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