Array: "Index was outside the bounds of the array"

19,559

Solution 1

There are many problems in that code, but, sticking to the problem on the question title I think that this line looks suspicious:

string NTLogin = Page.User.Identity.Name.ToString().Split(new char[] { '\\' })[1].ToUpper();  

what happen if the Page.User.Identity.Name doesn't contain a DOMAIN\USERNAME?

Could be rewritten as

string[] nameparts = Page.User.Identity.Name.ToString().Split(new char[] { '\\' });
string NTLogin = (nameparts.Length == 2 ? nameparts[1] : nameparts[0]).ToUpper();
if(NTLogin.Length == 0)
    return;            

Why this property could be the error? Look at this article

Solution 2

1) Your code is vulnerable to a SQL injection attack on the first select in getRoleForUser. You should use a SqlParameter.

2) without a stack trace it makes it difficult to determine where the error is. However, I think it maybe that the sql selects could return NO ROWS. So, whenever you do a r.Read, change it to if (!r.Read()) return;.

Again, if you post the stack trace we can be of better help.

Share:
19,559
user1221100
Author by

user1221100

Updated on August 21, 2022

Comments

  • user1221100
    user1221100 over 1 year

    I get the following error on my web application: "Index was outside the bounds of the array."

    The strange thing is, that the problem only comes on my webserver (Windows Server 2008 R2, .Net 4.0, Windows 7 Enterprise 64 Bit).

    When I debug the site in Visual Studio, it all works perfect

    The Code looks like this:

    I define an array and give it to the class "CheckUserRights"

    string NTLogin = Page.User.Identity.Name.ToString().Split(new char[] { '\\' })[1].ToUpper();
    string[] allowedRoles = new string[2] { "Administrator", "Superuser" };
    CheckUserRights Check = new CheckUserRights(NTLogin, allowedRoles);
    

    The class looks like this:

    //Lokale Variablen definieren
    string strUserName;
    string strRolename;
    string[] AllowedRoles;
    bool boolAuthorized;
    
    //Im Konstruktor definierte Werte übergeben.
    public CheckUserRights(string Username, string[] Roles)
    {
        this.strUserName = Username;
        this.AllowedRoles = Roles;
        getRoleForUser();
        checkRights();
    }
    ...
    ...
    

    I have searched for a solution after 4 hours, but I can't find anything. I am not a pro and that's the first time I have used arrays.

    Could it be a wrong configuration on the server?

    I am grateful for every help. Thanks!

    Update

    Solved, there was an problem in the server configuration. Solution is in the answer from Steve.