Issue in For-Each Loop with DataTable.Rows inside Web Service [vb.net] - vb.net

I have the following For Each loop inside of a web method that is part of a web service. It is meant to put all of the State names into one string so I can parse it out inside of an ajax control:
<WebMethod()> Public Function getState(ByVal country As String) As String
Dim oresult As New DataTableResults
Dim oData As New Location(_connstr)
oresult = oData.getState(country)
Dim states As String = ""
For Each row As DataRow In oresult.dtData.Rows
states = states & row.Item("StateText") & ","
Next
Return states
End Function
I tried stepping through it and it adds all of the items to the string, but an issue comes up when it exits the loop. It is then that it just shows that the webpage cannot be displayed and doesn't give any sort of error message other than 'HTTP 500 Internal Server Error.
Thanks

Related

vb.net How to declare thread and call functions with it

I'm trying to use a thread to translate every text found in the Windows Forms to make my system multi-language.
I have a separate class named 'Language' with a sub and a function, sub reads a language source file, and function translates by receiving and returning a string.
Then I have my first Windows Form where I declare my thread:
Dim ThreadTraductor As New Thread(AddressOf ...) 'don't know how to do it
Dim cultureInfo As New System.Globalization.CultureInfo(ConfigurationManager.AppSettings('en').ToString)
ThreadTraductor.CurrentCulture = cultureInfo
ThreadTraductor.CurrentUICulture = cultureInfo
Basically I'm creating this thread to have a background process translating every Windows Form that's opened during execution, problem is I don't know how to declare it properly since I don't want to include any parameter when declaring, but I want the thread to be called from different Forms with parameters to translate, and also I want the thread to use my translate method inside Language class, is that possible? How?
Please assist, I haven't use threads before.
Public Class Lenguaje 'Class used to read language source file and translate strings
Public dicIdioma As New Dictionary(Of String, String)
Public Sub LeerArchivo(ByVal Culture As String)
Dim vectorAux() As String
dicIdioma.Clear()
Try
Dim LectorArchivo As New StreamReader("C:\Users\Joaqo\Desktop\Dorian VB\DorianBdBv1.0\UI\bin\Debug\" + Culture + ".txt")
Dim line As String
While Not LectorArchivo.Peek = -1
line = LectorArchivo.ReadLine()
vectorAux = line.Split(":")
dicIdioma.Add(vectorAux(0), vectorAux(1))
End While
Catch ex As System.IO.FileNotFoundException
MessageBox.Show("No se encuentra el archivo de idioma.")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Function Traducir(ByRef frase As String) As String
Dim StringAux As String
For Each Item As String In dicIdioma.Keys
If Item = Char.ToLower(frase(0)) & frase.Substring(1) Then
StringAux = Char.ToUpper(dicIdioma.Item(Item)(0)) & dicIdioma.Item(Item).Substring(1)
frase = StringAux.Replace("_", " ")
ElseIf Item.Replace("_", " ") = Char.ToLower(frase(0)) & frase.Substring(1) Then
StringAux = Char.ToUpper(dicIdioma.Item(Item)(0)) & dicIdioma.Item(Item).Substring(1)
frase = StringAux.Replace("_", " ")
End If
Next
Return frase
End Function
End Class
Then I iterate every text object in my Windows Forms to translate them:
For Each Item As Label In Me.Controls.OfType(Of Label)()
Item.Text = Traductor.Traducir(Item.Text)
Next
For Each Item As Button In Me.Controls.OfType(Of Button)()
Item.Text = Traductor.Traducir(Item.Text)
Next
And it works just fine, but I'd be calling Traductor, Lenguaje's instance declared on my first interface, from the whole app, isn't that wrong somehow?
I was told that I should use Culture and CultureUI for this, but I'm not familiarized with that. What do you think? Sorry if I'm missing something, it's my first question here.

LDAP Vb.net simple query

I'm trying to create a vb.net code for a simple query through LDAP but having an issue and can't find where it is.
Dim ldapServerName As String = "xxx.test.intranet.xxx.ca"
Dim oRoot As DirectoryEntry = New DirectoryEntry("LDAP://" & ldapServerName & "/c=ca, DC=xxx,DC=corp,DC=xxx,DC=ca")
oRoot.Username = "ou=Tool,ou=applications,o=xxx,c=ca"
oRoot.Password = "something#2015"
Dim LDAPSearcher As New DirectorySearcher()
LDAPSearcher.Filter = "(&(employeenumber=6012589))"
Dim SearchResult As SearchResult = LDAPSearcher.FindOne()
Dim UserEntry As DirectoryEntry = SearchResult.GetDirectoryEntry()
EDTEST.Text = UserEntry.Properties("employeenumber").Value.ToString
it is giving me an error saying that the object is not valid. The searcher variable is in fact empty so it has to do with my query somehow.
This is my first time with LDAP¨and I have tried some of the solution i could find on the net but nothing is working so far.
Error: Object not set to an instance of an object.
Unless you're adding another attribute to search by, you don't need the AND operator in your filter syntax - a search for simply (employeenumber=6012589) should work just fine.
If do you have another attribute you'd like to search by, the filter syntax would be similiar to what you have now, only with the additional attribute :
(&(employeenumber=6012589)(objectClass=user))
EDIT:
I put together an example using the lower level System.DirectoryServices and System.DirectoryServices.Protocols namespaces. This helps break up the actual login and search functions, and will also provide better context when errors occur. For the example, I've replaced all of my variables with the ones you're using in your question. I tested this against our own Active Directory instance over unsecured port 389 using my creds and a base domain similar to the one you're using.
Imports System.DirectoryServices.Protocols
Imports System.Net
Module Module1
Sub Main()
' setup your creds, domain, and ldap prop array
Dim username As String = "ou=Tool,ou=applications,o=xxx,c=ca"
Dim pwd As String = "something#2015"
Dim domain As String = "DC=xxx,DC=corp,DC=xxx,DC=ca"
Dim propArray() As String = {"employeenumber"}
' setup your ldap connection, and domain component
Dim ldapCon As LdapConnection = New LdapConnection("xxx.test.intranet.xxx.ca:389")
Dim networkCreds As NetworkCredential = New NetworkCredential(username, pwd, domain)
' configure the connection and bind
ldapCon.AuthType = AuthType.Negotiate
ldapCon.Bind(networkCreds)
' if the above succceeded, you should now be able to issue search requests directly against the directory
Dim searchRequest = New SearchRequest(domain, "(employeenumber=6012589)", SearchScope.Subtree, propArray)
' issue the search request, and check the results
Dim searchResult As SearchResponse = ldapCon.SendRequest(searchRequest)
Dim searchResultEntry As SearchResultEntry
If (searchResult.Entries.Count > 0) Then ' we know we've located at least one match from the search
' if you're only expecting to get one entry back, get the first item off the entries list
searchResultEntry = searchResult.Entries.Item(0)
' continue to do whatever processing you wish against the returned SearchResultEntry
End If
End Sub
End Module

WCF Error - An error occurred while receiving the HTTP response to http://localhost:50750/*******.svc

I am receiving the following error while debugging.
An error occurred while receiving the HTTP response to http://localhost:50750/FIGService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Now I have seen many posts where people have had that error, I have cut my WCF down to absolute barebones and I am still getting the error, I am running the following:
Public Function TestXML(ByVal Username As String, ByVal Password As String, ByVal XML As String) As XmlDocument Implements FreshCloud.TestXML
Dim ReturnXMLDoc As New XmlDocument()
If ValidateLogin(Username, Password) <> False Then
ReturnString = "<FreshLead><Result><Message>Failed - XSD Validation</Message><DateTime>" & Date.Now.ToString & "</DateTime></Result></FreshLead>"
ReturnXMLDoc.LoadXml(ReturnString)
Return ReturnXMLDoc
End If
End Function
Don't worry about the uselessness of the code I literally just copy and pasted various bits to run a test, this is than ran with a simple test app with a button:
Dim client As FreshCloudClient = New FreshCloudClient()
Dim strXML = client.TestXML("ABC", "BS", "Doesn't Matter")
Dim strTest = strXML
client.Close()
I receive the error just returning the above, please any light that can be shed would be grateful this is a big project that I have had to sink my teeth into a Microsoft's vague error messages do not help a learner.
Cheers! :)
UPDATE
After digging through the logs for WCF I stumbled across this:
Type 'System.Xml.XmlDocument' is an invalid collection type since it does not have a valid Add method with parameter of type 'System.Object'.
Can anyone share with me why this exception would be thrown up by WCF?
Cheers.
UPDATE 2
OK so following Lerners advice I have now got the following:
Public Function TestXML(ByVal Username As String, ByVal Password As String, ByVal XML As String) As XElement Implements FreshCloud.TestXML
Dim ReturnXMLDoc
If ValidateLogin(Username, Password) <> False Then
ReturnString = "<FreshLead><Result><Message>Failed - XSD Validation</Message><DateTime>" & Date.Now.ToString & "</DateTime></Result></FreshLead>"
ReturnXMLDoc = XElement.Parse(ReturnString)
Return ReturnXMLDoc
End If
End Function
On my client side of have said to put the response to a variable and Console.WriteLine the variable and it just returned System.Object?
Surely this should return the XML as it shows in ReturnXMLDoc variable when I debug on the WCF side of things?
UPDATE 3
WORKING!
Lerner put me in the right ballpark and I just had to update the Service Definitions from within my 'Client' Application.
Cheers.
Return XElement instead of XDocument, XElement is IXmlSerializable.
var xml = XElement.Parse(ReturnString);
return xml;

vb.net: listbox.items.add() throws exception in same class

I'm not even sure I understand this situation enough to come up with a proper title. I come from a modest understanding of VB6 and having to climb a steep learning curve for VB 2010.
I am trying to create a multi-client server program that will communicate with my Enterprise iPhone app. I found a relatively simple example to build upon here: http://www.strokenine.com/blog/?p=218. I have been able to modify the code enough to make it work with my app, but with one glitch: I can't get access to the controls on the form to add items, even though the method is invoked within the form's class. (I tried this on the original code too, and it does the same thing. I don't know how the author managed to get it to work.)
Here's the code segment in question:
Public Class Server 'The form with the controls is on/in this class.
Dim clients As New Hashtable 'new database (hashtable) to hold the clients
Sub recieved(ByVal msg As String, ByVal client As ConnectedClient)
Dim message() As String = msg.Split("|") 'make an array with elements of the message recieved
Select Case message(0) 'process by the first element in the array
Case "CHAT" 'if it's CHAT
TextBox3.Text &= client.name & " says: " & " " & message(1) & vbNewLine 'add the message to the chatbox
sendallbutone(message(1), client.name) 'this will update all clients with the new message
' and it will not send the message to the client it recieved it from :)
Case "LOGIN" 'A client has connected
clients.Add(client, client.name) 'add the client to our database (a hashtable)
ListBox1.Items.Add(client.name) 'add the client to the listbox to display the new user
End Select
End Sub
Under Case "LOGIN" the code tries to add the login ID to the listbox. It throws an exception: "A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll" The listbox (all controls, for that matter) is in the same class, Server.vb and Server.vb [Design].
The data comes in from another class that is created whenever a client logs on, which raises the event that switches back to the Server class:
Public Class ConnectedClient
Public Event gotmessage(ByVal message As String, ByVal client As ConnectedClient) 'this is raised when we get a message from the client
Public Event disconnected(ByVal client As ConnectedClient) 'this is raised when we get the client disconnects
Sub read(ByVal ar As IAsyncResult) 'this will process all messages being recieved
Try
Dim sr As New StreamReader(cli.GetStream) 'initialize a new streamreader which will read from the client's stream
Dim msg As String = sr.ReadLine() 'create a new variable which will be used to hold the message being read
RaiseEvent gotmessage(msg, Me) 'tell the server a message has been recieved. Me is passed as an argument which represents
' the current client which it has recieved the message from to perform any client specific
' tasks if needed
cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing) 'continue reading from the stream
Catch ex As Exception
Try 'if an error occurs in the reading purpose, we will try to read again to see if we still can read
Dim sr As New StreamReader(cli.GetStream) 'initialize a new streamreader which will read from the client's stream
Dim msg As String = sr.ReadLine() 'create a new variable which will be used to hold the message being read
RaiseEvent gotmessage(msg, Me) 'tell the server a message has been recieved. Me is passed as an argument which represents
' the current client which it has recieved the message from to perform any client specific
' tasks if needed
cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf read, Nothing) 'continue reading from the stream
Catch ' IF WE STILL CANNOT READ
RaiseEvent disconnected(Me) 'WE CAN ASSUME THE CLIENT HAS DISCONNECTED
End Try
End Try
End Sub
I hope I am making sense with all this. It all seems to bounce back and forth, it seems so convoluted.
I've tried using Me.listbox1 and Server.listbox1 and several other similar structures, but to no avail.
I'm reading a lot about Invoke and Delegates, but would that be necessary if the method and the control are in the same class? Or do I have a fundamental misperception of what a class is?
Many thanks for any help I can get.
Private Delegate Sub UpdateListDelegate(byval itemName as string)
Private Sub UpdateList(byval itemName as string)
If Me.InvokeRequired Then
Me.Invoke(New UpdateListDelegate(AddressOf UpdateList), itemName)
Else
' UpdateList
' add list add code
ListBox1.Items.Add(itemName)
End If
End Sub
Add above, then replace:
ListBox1.Items.Add(client.name)
to
UpdateList(client.name)
Does it work? check the syntax, may have typo as I type it.

VB.NET Remove user from active directory

Hi I am trying to create a VB.NET application which will (hopefully) reduce some time spent on some of my departments helpdesk calls. The part that I am stuck with is how to use VB.NET to remove a user from a group. The following is code that I have been playing with:
Public Shared Sub RemoveUserFromGroup(ByVal deUser As String, ByVal GroupName As String)
Dim entry As DirectoryEntry = ADEntry()
Dim mySearcher As DirectorySearcher = New DirectorySearcher(entry)
mySearcher.Filter = "(&(ObjectClass=Group)(CN=" & GroupName & "))"
mySearcher.PropertiesToLoad.Add("OrganizationalUnit")
mySearcher.PropertiesToLoad.Add("DistinguishedName")
mySearcher.PropertiesToLoad.Add("sAMAccountName")
Dim searchResults As SearchResultCollection = mySearcher.FindAll()
If searchResults.Count > 0 Then
Dim group As New DirectoryEntry(searchResults(0).Path)
Dim members As Object = group.Invoke("Members", Nothing)
For Each member As Object In CType(members, IEnumerable)
Dim x As DirectoryEntry = New DirectoryEntry(member)
MessageBox.Show(x.Properties("sAMAccountName").Value)
If x.Properties("sAMAccountName").Value = deUser Then
MessageBox.Show(searchResults.Item(0).Path.ToString)
MessageBox.Show(x.Properties("sAMAccountName").Value)
'group.Invoke("Remove", New Object() {x.Properties("OrganizationalUnit").Value})
group.Properties("member").Remove(x.Properties("OrganizationalUnit").Value)
End If
Next
End If
When I run the program, I recevie a COMException was unhandled, unspecified error at the group.properties line. When using group.invoke I receive the error TargetInvocationException was unhandled.
My aim is to pass as a string the username (sAMAccountName) and the groupname (sAMAccountName) to the function which will locate the user and remove them from the group.
I am new to VB.NET and would appreciate any assistance people can provide.
I am coding in .NET 2.0 as I am unsure if the server it will live on will have 3.5 installed.
Well the error message 0x80004005 E_FAIL Unspecified failure is not very helpful. I often get frustrated when working with Active Directory.
Try changing line:
group.Properties("member").Remove(x.Properties("OrganizationalUnit").Value)
to
group.Invoke("Remove", New Object() {x.Path.ToString()})
If you need more reference take a look at this article on VB.net Heaven by Erika Ehrli. The article covers various use cases with Active Directory.
I hope that helps.