Glory Raj
Glory Raj

Reputation: 17701

need to check all items in string array with if condition

i have got the below code to check whether the login user access to menu item

but if first item fails the if condition it is redirecting to error page, but i need to check second item from that string array with if condition even the first item fails the if condition ...

please find the below given code for test..

var count = 0;
string[] strPageId = PageId.Split(';');


foreach (string menuPageId in strPageId)
{
       if (objDALookup.IsPageVisible(PageType,Int32.Parse(menuPageId), role, AcctId) == false)
       {
           Session["ErrorInfo"] = "Access denied, please contact system administrator.";
           new Lib.Utils.Log().logInfo("FORCE_ACCESS", strUser + " tried to access PageId:" + PageId + " PageType:" + PageType);
           Response.Redirect(ConfigurationManager.AppSettings["ACCESS_DENIED_URL"], true);
       }
       else
       {
            count++;
            if (count == strPageId.Length) break;

       }
 } 

Upvotes: 1

Views: 81

Answers (1)

Adil
Adil

Reputation: 148180

You can make condition something like this by figuring out condition in loop and executing the action outside loop once it is decided.

bool access = false;
foreach (string menuPageId in strPageId)
{    
   if (objDALookup.IsPageVisible(PageType,Int32.Parse(menuPageId), role, AcctId) == true)
   {
        access = true; 
        break;
   }
}

if(!access)
{

    Session["ErrorInfo"] = "Access denied, please contact system administrator.";
           new Lib.Utils.Log().logInfo("FORCE_ACCESS", strUser + " tried to access PageId:" + PageId + " PageType:" + PageType);

     Response.Redirect(ConfigurationManager.AppSettings["ACCESS_DENIED_URL"], true);
}

OR

You can use linq

bool access = strPageId.Any(s=> objDALookup.IsPageVisible(PageType,Int32.Parse(menuPageId), role, AcctId) == true);

if(!access)
{

} 

Upvotes: 2

Related Questions