Solved

Show or Hide a field based on Role status.

Posted on 2007-11-14
12
768 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
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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

813 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now