"IF" code is not working inside for each? - vb.net

so im learning to use socket and thread things in the networking software. so far, the software (which is not created by me) is able to chat in multiple group, but i'm tasked to allow user to code whisper feature. However, im stuck in the coding area, which im sure will work if the "if" function work inside "for each" function, anyhow here is my code mainly
Private clientCollection As New Hashtable()
Private usernameCollection As New Hashtable()
clientCollection.Add(clientID, CData)
usernameCollection.Add(clientID, username)
oh and before i forgot, the code above and below is on the server form page
on the client side, i write the code:
writer.write("PMG" & vbnewline & txtReceiverUsername & Message)
then next is the checking part on the server reading the message:
ElseIf message.Substring(0, 3) = "PMG" Then
'filter the message, check who to send to
Dim newMessage As String = message.Substring(3)
Dim messagearray As String() = newMessage.Split(vbNewLine)
Dim receiver As String = messagearray(1)
'0 = "", 1 = receiver, 2 = message
as i write before, clientcollection contain (clientID , connection data*) and usernamecollection contain (clientID, username). In my case, i only have the username data, and i need to trace it until the connection data on clientcollection hash table.
'find realid from usernamecollection, then loop clientcollection
Dim clientKey As String = 0
For Each de As DictionaryEntry In usernameCollection
'''''
'this if part Is Not working
If de.Value Is receiver Then
clientKey = de.Key
End If
'''''
Next de
'match objKey with clientcollection key
For Each dec As DictionaryEntry In clientCollection
If dec.Key = clientKey Then
Dim clients As ClientData = dec.Value
If clients.structSocket.Connected Then
clients.structWriter.Write("PMG" & messagearray(2))
End If
End If
Next dec
End If
so, how do i know that the if part is the wrong one? simply i tried these code before the "next de" code
For Each client As ClientData In clientCollection.Values
If client.structSocket.Connected Then
client.structWriter.Write("PMG" & "receiver:" & messagearray(1))
client.structWriter.Write("PMG" & "loop username: " & de.Value)
client.structWriter.Write("PMG" & "loop key: " & de.Key)
client.structWriter.Write("PMG" & "receiver key:" & clientKey)
End If
Next
the code allow me to check the de.key and de.value. they were correct, however the only thing that did not work is the code inside the "if" area.
Can anyone suggest other code maybe beside "if de.key = receiver"? I've also tried using the if de.key.equal(receiver) and it did not work too

Related

Telnet (winsock) connection in VBA - class not registered

I have GSM gateway that use telnet for sending/recivieng SMS. I'am making a small app in my ms-access for sending sms notifications for my clients. For that I need winsock connection from my client computer -> gsm gateway. It supposed to be easy :)
I can't establish an object. I'm receiving run-time error -2147221164(80040154) - Class not registered. Error is indicated in "Set winsock = ..." line. I have added reference MS Winsock Control 6.0 (SP6) - MSWINSCK.OCX. I have a feeling this is a problem with reference, but I don't have any idea how to correct it (code below is simplified) :( .
Option Explicit
Private WithEvents Winsock1 As Winsock
Sub Start_Telnet_Session()
Dim Data As String
Dim Winsock1
Set Winsock1 = New MSWinsockLib.Winsock
Winsock1.RemoteHost = "192.168.1.1"
Winsock1.RemotePort = "23"
Winsock1.connect
Do Until Winsock1.State = 7
DoEvents
If Winsock1.State = sckError Then
Exit Sub
End If
Loop
Winsock1.SendData "user" & vbCrLf
Winsock1.SendData "pass" & vbCrLf
Dim I As Integer
I = 5
While TelnetCommands <> ""
Winsock1.SendData "TelnetCommands" & vbCrLf
Winsock1.GetData Data
Data = VBA.Replace(Data, vbLf, "")
Data = VBA.Replace(Data, vbCr, vbNewLine)
MsgBox Data
I = I + 1
Wend
Winsock1.Close
End Sub

Create an appointment with required attendees in Lotus Notes using VBA in Access 2013

I am attempting to create a check out log for inventory in Access 2013. During this process you will create an appointment on the expected return date in the Lotus Notes 9 calendar. I have found enough examples to do this successfully. However I am getting stuck when trying to add people to the "RequiredAttendees" field. I am pretty sure that I am using the right field name but i keep getting the following error:
Run-time error '-2147417851 (80010105)': Automation error. The server
threw an exception.
Everything else works fine except the part that tries to add attendees. I know Lotus Notes 9 is old and I know Access 2013 is old but those are the tools I am required to work with. Any help would be appreciated.
Public Function test() As Variant
Dim StartTime As Date
Dim MailDbName As String
Dim CalenDoc As Object
Dim WorkSpace As Object
Dim AppDate As String
Dim AppTime As String
Dim Subject As String
Set WorkSpace = CreateObject("Notes.NOTESUIWORKSPACE")
AppDate = InputBox(Prompt:="Enter the return date:")
'Subject = InputBox(Prompt:="Enter the subject:")
'AppTime = InputBox(Prompt:="Enter the time:")
MailDbName = "mail\User.nsf"
strSTime = CStr(Timex)
Set CalenDoc = WorkSpace.COMPOSEDOCUMENT("MailServer", MailDbName, "Appointment")
CalenDoc.FIELDSETTEXT "AppointmentType", "3"
CalenDoc.Refresh
CalenDoc.FIELDSETTEXT "StartDate", CStr(AppDate)
CalenDoc.FIELDSETTEXT "EndDate", CStr(AppDate)
CalenDoc.FIELDSETTEXT "StartTime", "12:00 PM"
CalenDoc.FIELDSETTEXT "EndTime", "12:00 PM"
CalenDoc.FIELDSETTEXT "Subject", "Test"
GetUser = Environ("UserName")
EmailAddress = GetUser & "#company.com"
If EmailAddress = "User1#company.com" Then
CalenDoc.FIELDSETTEXT "RequiredAttendees", "User2#company.com" & "," & "User3#company.com"
CalenDoc.Refresh
ElseIf EmailAddress = "User2#company.com" Then
CalenDoc.FIELDSETTEXT "RequiredAttendees", "User1#company.com" & "," & "User3#company.com"
CalenDoc.Refresh
ElseIf EmailAddress = "User3#company.com" Then
CalenDoc.FIELDSETTEXT "RequiredAttendees", "User2#company.com" & "," & "User1#company.com"
CalenDoc.Refresh
Else
MsgBox (EmailAddress & "is not a valid email address.")
End If
'CalenDoc.gotoField "Body"
'CalenDoc.InsertText Body
CalenDoc.Refresh
'CalenDoc.Save
'CalenDoc.Close
'Set CalenDoc = Nothing
'Set WorkSpace = Nothing
I think you've been confused by looking at examples that use the back-end COM classes instead of, or maybe in addition to, examples that use the front-end OLE classes. You are using Notes.NOTESUIWORKSPACE - OLE, instead of Lotus.NotesSession - COM. That means you have to use the actual editable fields on the Appointment form, which are sometimes not what you expect them to be. In some cases, these front-end fields are not the same as the items that will end up being stored in the back-end document - and it's the back-end item names that are typically documented because they are the ones that get stored in the note.
RequiredAttendees is the stored item name, but you are getting the automation error because it's a computed field on the Appointment form, not an editable field.
Since you are using OLE, you need to enter the data into the "EnterSendTo" field. The data that you (or a user) puts in there will, in fact, end up in the RequiredAttendees item due to the magic that goes on in the formulas and scripts associated with the Appointment form.

Get First & Last Name of All AD Accounts

I'm looking for the quickest and easiest way to retrieve all Active Directory account's first & last names. The intention is to have a string list which contains all names from the Active Directory, for the purpose of auto-completion in a textbox in a small Visual Basic application used for unlocking accounts.
Usage Scenario:
On form load the application generates the list of names from the AD. I'm expecting this to take around 10-15 seconds as there's 4,500 accounts on the AD. Each name is added to a string list for use with the auto completion.
The user types the name Garry into textbox1 and the auto complete suggests all Garry's in the AD, by using a string list. I know how to do this easily, I just dont know how to populate the list with user's names efficiently.
There's a lot of samples on accessing the AD, but none which show how to loop through it. I thought asking on here would help both myself and other users in a similar usage case.
The code I have so far for accessing a single account is shown below, however I need to loop through all AD accounts and retrieve their First & Last names.
Current Code to access single account:
'Domain is declared with the LDAP path
'UserName is declared with textbox1.text value
Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & Domain)
Dim ADSearch As New System.DirectoryServices.DirectorySearcher(ADEntry)
ADSearch.Filter = ("(samAccountName=" & UserName & ")")
ADSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree
Dim UserFound As System.DirectoryServices.SearchResult = ADSearch.FindOne()
If Not IsNothing(UserFound) Then
Log.AppendLine("Account found, loading checks...")
Dim Attrib As String = "msDS-User-Account-Control-Computed"
Dim User As System.DirectoryServices.DirectoryEntry
User = UserFound.GetDirectoryEntry()
User.RefreshCache(New String() {Attrib})
'Display user account details
txtLogin.Text = User.Properties("userPrincipalName").ToString
txtName.Text = User.Properties("givenName").ToString & " " & User.Properties("sn").ToString
else
'User not found
end if
Any help would be much appreciated, even in C#.
You can use the same ADEntry variable as above and do something like this. This only adds a user to the list if they have both a first and last name.
Dim listNames As New AutoCompleteStringCollection
Using ADSearch As New DirectoryServices.DirectorySearcher(ADEntry, "(&(objectCategory=person)(objectClass=user))", {"givenName", "sn"}, DirectoryServices.SearchScope.Subtree)
For Each user As DirectoryServices.SearchResult In ADSearch.FindAll
Try
listNames.Add(user.GetDirectoryEntry.Properties("givenName").Value.ToString + " " + user.GetDirectoryEntry.Properties("sn").Value.ToString)
Catch ex As Exception
End Try
Next
End Using
With TextBox1
.AutoCompleteCustomSource = listNames
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.CustomSource
End With

How do I display the value of a shared parameter using an Element collector in Revit?

Thanks in advance for the help. I have no idea what I'm doing wrong and it's becoming very frustrating. First, a little background...
Program: Revit MEP 2015
IDE: VS 2013 Ultimate
I have created a Shared Parameter file and added the parameters in that file to the Project Parameters. These parameters have been applied to Conduit Runs, Conduit Fittings, and Conduits.
I'm using VB.NET to populate the parameters with no issue. After the code runs, I can see the expected text applied in the elements property window. Here is the code used to populate the values:
Populate:
Dim p as Parameter = Nothing
Dim VarName as String = "Parameter Name"
Dim VarVal as String = "Parameter Value"
p = elem.LookupParameter(VarName) <-- elem is passed in to the function as an Element
If p IsNot Nothing Then
p.Set(VarVal)
End if
Here's where I run into the error. When I attempt to retrieve the value, I am able to get the parameter by the parameter's definition name, but the value is always blank. Here is the code used to retrieve...
Try
For Each e As Element In fec.OfCategory(BuiltInCategory.OST_ConduitRun)
sTemp = sTemp & "Name: " & P.Definition.Name & vbCrLf & "Value: " & P.AsString & vbCrLf & "Value As: " & P.AsValueString & vbCrLf & vbCrLf
sTemp2 = sTemp2 & "Name: " & GetParamInfo(P, doc)
Next
MessageBox.Show(sTemp)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
The message box shows all of the parameter names correctly, and for the Revit parameters it gives me a value. The Shared parameters, however, only show the parameter names, the values are always blank. Is there another way that I'm supposed to be going about this? Oddly, I'm able to see the shared parameter values if I use a reference by user selection like so...
Dim uiDoc As UIDocument = app.ActiveUIDocument
Dim Sel As Selection = uiDoc.Selection
Dim pr As Reference = Nothing
Dim doc As Document = uiDoc.Document
Dim fec As New FilteredElementCollector(doc)
Dim filter As New ElementCategoryFilter(BuiltInCategory.OST_ConduitRun)
Dim sTemp As String = "", sTemp2 As String = ""
Dim elemcol As FilteredElementCollector = fec.OfCategory(BuiltInCategory.OST_ConduitRun)
Dim e As Element = Nothing, el As Element = Nothing
Dim P As Parameter
pr = Sel.PickObject(ObjectType.Element)
e = doc.GetElement(pr)
For Each P in e.Paramters
sTemp = sTemp & "Name: " & P.Definition.Name & vbCrLf & "Value: " & P.AsString & vbCrLf & "Value As: " & P.AsValueString & vbCrLf & vbCrLf
sTemp2 = sTemp2 & "Name: " & GetParamInfo(P, doc)
Next
MessageBox.Show(sTemp)
With the method above, when the user selects the object directly, I can see the values and the names of shared parameters. How are they different?
Is there some sort of binding that I should be looking at when the value is set to begin with? Thanks in advance for everyone's help.
Regards,
Glen
Holy Bejeesus... I figured it out, but I'm not sure why the methods are that different from each other... if anyone had any insight, that'd be great.
I wanted to post the answer here, just in case anyone else is fighting with the same thing, so... you can see the method I was using to try to read the parameters above. In the method being used now there are only a couple of things that are different... 1) An element set... 2) An active view Id was added as a parameter to the FilteredElementCollector... 3) A FilteredElementIterator was implemented.
As far as I can tell it's the iterator that's making it different... can anyone explain what it's doing differently?
Below is the method that actually works...
Public Sub Execute(app As UIApplication) Implements IExternalEventHandler.Execute
Dim prompt As String = ""
Dim uiDoc As UIDocument = app.ActiveUIDocument
Dim doc As Document = uiDoc.Document
Dim ElemSet As ElementSet = app.Application.Create.NewElementSet
Dim fec As New FilteredElementCollector(doc, doc.ActiveView.Id)
Dim fec_filter As New ElementCategoryFilter(BuiltInCategory.OST_Conduit)
fec.WhereElementIsNotElementType()
fec.WherePasses(fec_filter1)
Dim fec_i As FilteredElementIterator = fec.GetElementIterator
Dim e As Element = Nothing
fec_i.Reset()
Using trans As New Transaction(doc, "Reading Conduit")
trans.Start()
While (fec_i.MoveNext)
e = TryCast(fec_i.Current, Element)
ElemSet.Insert(e)
End While
Try
For Each ee As Element In ElemSet
GetElementParameterInformation(doc, ee)
Next
Catch ex As Exception
TaskDialog.Show("ERROR", ex.Message.ToString)
End Try
trans.Commit()
End Using
End Sub
At any rate, thanks for any help that was offered. I'm sure it won't be the last time that I post here.
Regards,
Runnin

VBA Code to Create Lotus Notes Email - CC Emails Not Working

I have some VBA code that takes the various email parts as inputs and creates an email message in Lotus Notes, and sends it from a group mailbox. It sends the email out to a recipient and CC recipients, and then leaves a copy of the message in the "Sent" box of a group email account. I think the sent message in that box is sort of a dummy, as it is perhaps not the exact message as it was sent.
This works, and sends the message to the SendTo, and to the first CC address. However, if I have a second CC address, it turns the ending of the second address into gibberish. For example, if the SendTo is "mike#someemail.com", and the CC is "john#someemail.com, jim#someemail.com"... in the Sent box it appears to have sent it to mike#someemail.com, and CC to john#someemail.com and jim#someemail.com. However, the actual mail is only received by john, and the CC looks like this: "john#someemail.com, jim#pps.rte_to_v" and jim never gets the message.
On another message, the second CC ends up being jim#vwall11.com. I haven't found a pattern to the gibberish it puts at the end of the CC line instead of the correct address. It took us awhile to learn about the problem since it looks correct in the Sent mailbox.
Here's the code I'm using. I'm changing the server names, etc, but all relevant code is intact.
Private Sub TestEmail()
Call EmailFromADT("mike#somemail.com", "john#somemail.com, jim#somemail.com", "test subject", "test message", _
"", "", "", "")
End Sub
Function EmailFromADT(strSendTo As String, strCopy As String, strSubject As String, _
strText1 As String, strText2 As String, strText3 As String, _
strText4 As String, strText5 As String)
Dim notesdb As Object
Dim notesdoc As Object
Dim notesrtf As Object
Dim notessession As Object
Dim i As Integer
Set notessession = CreateObject("Notes.Notessession")
''''''''Group Mailbox'''''''''''''''''''''''''''''''''''''''''''''''''
Set notesdb = notessession.GetDatabase("servername", "mailin\notesaddr.nsf")
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Open the mail database in notes
If notesdb.IsOpen = True Then
'Already open for mail
Else
notesdb.OPENMAIL
End If
Set notesdoc = notesdb.CreateDocument
Call notesdoc.ReplaceItemValue("Subject", strSubject)
Set notesrtf = notesdoc.CreateRichTextItem("body")
Call notesrtf.AppendText(strText1 & vbCrLf & strText2 & vbCrLf & strText3 & vbCrLf & strText4 & vbCrLf & strText5)
notesdoc.SendTo = strSendTo
notesdoc.CopyTo = strCopy
notesdoc.from = UserName()
''''''''Group Mailbox'''''''''''''''''''''''''''''''''''''''''''''''''
notesdoc.principal = "Group Team"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
notesdoc.BlindCopyTo = strBCC
Call notesdoc.Save(True, False)
notesdoc.SaveMessageOnSend = True
Call notesdoc.Send(False, strSendTo)
Set notessession = Nothing
End Function
To have multiple values in an item in a Document, you need to use an array.
Try this:
dim varCopyTo as Variant
varCopyTo = Split( strCopyTo, "," )
call notesDoc.Replaceitemvalue( "CopyTo", varCopyTo )
You could also write notesDoc.CopyTo=varCopyTo, but it is better (more secure, slightly better performance) to use ReplaceItemValue.
In addition you should add Call notesDoc.ReplaceItemValue("Form", "Memo" ) after creating the document, so that the server/client does not have to "guess" what kind of document you are creating.
notesdoc.CopyTo wants an array, not a comma-delimted string on the right hand side of the assignment. Each element in the array should be an individual address. By passing in a comma-delimited string, you're essentially passing in a single invalid address as far as Notes and Domino are concerned. I'm not entirely sure why that's being transformed in the peculiarly random way that it is, but I am sure it's definitely not going to be right that way.
And better than using the shorthand form (notesdoc.CopyTo = ...) for this code, you should probably be using Call notesdoc.ReplaceItemValue, like you do with the Subject, but passing in an array there.