Solved

Show or Hide a field based on Role status.

Posted on 2007-11-14
12
779 Views
Last Modified: 2013-11-07
ASP.net 2.0
I'm using Roles in my web site.
How do I create and If statment to say:
IF (User Role = Administrator) then
<asp:CommandField ShowEditButton="True" />
ELSE
<asp:CommandField ShowEditButton="False" />
END IF

Then were do I put this code (in the code behide? or on the page it's self)?


<asp:GridView ID="GridView2" runat="server" DataSourceID="XmlDataSource1">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
        </asp:GridView>
0
Comment
Question by:quest_capital
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
12 Comments
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20285888
Ok here goes,

This code for example will give you all the role info for the current user

        private void Form1_Load(object sender, EventArgs e)
        {
            AppDomain myDomain = Thread.GetDomain();

            myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;

            Console.WriteLine("{0} belongs to: ", myPrincipal.Identity.Name.ToString());

            Array wbirFields = Enum.GetValues(typeof(WindowsBuiltInRole));

            foreach (object roleName in wbirFields)
            {
                try
                {
                    Console.WriteLine("{0}? {1}.", roleName,
                        myPrincipal.IsInRole((WindowsBuiltInRole)roleName));
                }
                catch (Exception)
                {
                    Console.WriteLine("{0}: Could not obtain role for this RID.",
                            roleName);
                }
            }
        }

http://msdn2.microsoft.com/en-us/library/system.security.principal.windowsprincipal.isinrole(VS.71).aspx


So your answer really is

            AppDomain myDomain = Thread.GetDomain();

            myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;

            if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                  MyButton.Visible = true
            }
             else
             {
                  MyButton.Visible = false
             }

you will also need to add these to the top of your class
using System.Threading;
using System.Security.Principal;


Note also that you can check for other roles using WindowsBuiltInRole, administrator is defined in the example

RedK
0
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20285903
That is all C# code for the codebehind class

You could also structure it like this, create a function like so in your codebehind

public bool AmIAdmin()
{
            AppDomain myDomain = Thread.GetDomain();

            myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;

            if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                  return = true;
            }
             else
             {
                  return = false;
             }
}

then anywhere in the codebehind you can go

if (AmIAdmin)
{
       MyButton.Visible = true;
}
else
{
       MyButton.Visible = false;
}
0
 
LVL 2

Expert Comment

by:telefonia
ID: 20285919
may this help:
1- add:
<asp:CommandField id="button1" runat="server"  ShowEditButton="True" />
2. OnDataBind() event use it.
IF (User Role = Administrator) then
ctype(e.item.findcontrol("button1"), CommandField).ShowEditButton="True"
ELSE
ctype(e.item.findcontrol("button1"), CommandField).ShowEditButton="False"
END IF
0
Is Your Team Achieving Their Full Potential?

74% of employees feel they are not achieving their full potential. With Linux Academy, not only will you strengthen your team's core competencies but also their knowledge of of the newest IT topics.

With new material every week, we'll make sure that you stay ahead of the game.

 

Author Comment

by:quest_capital
ID: 20285944
RedKelvin:

That seem much to complecated to just get the users role.
this does not work be wouldn't it be something simple like
if(Roles.Equals("Admin"))
        {
}
This should be stored in a session right?
0
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20285954
Something else, any control in your markup, that you want to expose to the codebehind will need an ID, such as

ID="MyButton"

and you will need to set the runat property to server

runat="server"
0
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20285965
Ah yes you are right

It is User.IsinRole

What I posted before gets the machine role, User.IsinRole gets the asp role
0
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20285969
0
 

Author Comment

by:quest_capital
ID: 20286004
RedKelvin:

User.IsInRole
tells you what role the user is in

I just need to do something like
if(Roles.Equals("Admin"))
        {
            Label1.Text = "Admin";
        }
but this gives you an error
0
 
LVL 22

Expert Comment

by:RedKelvin
ID: 20286086
Yeah, I reckon you need to do it with IsInRole, like this

if(User.IsInRole("Admin"))
        {
            Label1.Text = "Admin";
        }
0
 

Author Comment

by:quest_capital
ID: 20289167
RedKelvin:
if(User.IsInRole("Admin"))
        {
            Label1.Text = "Admin";
        }
and
if(Roles.Equals("Admin"))
        {
            Label1.Text = "Admin";
        }
but this gives you an error

do not work
0
 

Author Comment

by:quest_capital
ID: 20289578
if(User.IsInRole("Admin"))
        {
            Label1.Text = "Admin";
        }
Do I need a namespce for this?
Is this just a VB thing?
do I need to ad like:
this.user.IsInRole
or
bah.user.IsInRole
0
 
LVL 6

Accepted Solution

by:
ventaur earned 500 total points
ID: 20290425
Use the Page property if your code is in a user control. It'll work even if you're on a page:

if (Page.User.IsInRole("Admin")) {
  Label1.Text = "Admin";
}


To answer your original question though, setup your grid view like this:

<asp:GridView ID="GridView2" runat="server" DataSourceID="XmlDataSource1" OnPreRender="GridView2_PreRender">
  <Columns>
    <asp:CommandField ShowEditButton="True" />
  </Columns>
</asp:GridView>

Notice the OnPreRender event setup. Next, either in code-behind or in a server-side script tag, add the attached code to show/hide that command column entirely, based on the user's role just before the grid renders.
protected void GridView2_PreRender(object sender, EventArgs e) {
  if (!Page.User.IsInRole("Admin")) {
    // Get the first column by index.
    // * If you change the position of the CommandField, use the appropriate index here.
    int ColIndex = 0;
    GridView2.Columns[ColIndex].Visible = false;
  }
}

Open in new window

0

Featured Post

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question