Returning information from webservice. I have made a class for the return object. But I get the following error message when assigning results to each list item.
When invoking my webservice I am returned with the following message:
System.ArgumentOutOfRangeException: Index was out of range. Must be
non-negative and less than the size of the collection. Parameter name:
index at System.ThrowHelper.ThrowArgumentOutOfRangeException()
at System.Collections.Generic.List`1.get_Item(Int32 index) at
NewUser.ADMethods.GetUserInfo(String userName)
Please help!
public class UserInformation
{
public string givenname { get; set; }
public string surname { get; set; }
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<UserInformation> GetUserInfo(string userName)
{
// Gather User Info
// Invoke Directory Searcher & Directory Entry
DirectorySearcher ds = new DirectorySearcher();
// Apply filter to search
ds.Filter = "(&(objectCategory=user)(samaccountname=" + userName + "))";
SearchResult sr = ds.FindOne();
List<UserInformation> UserInfo = new List<UserInformation>();
UserInfo[0].givenname = sr.Properties["givenname"].ToString();
return UserInfo;
}
Your problem is that you are creating a list, which is initially empty, and then trying to access value for a first item, which does not exist yet.
You have to create the item and then add it to the list: