?
Solved

Show or Hide a field based on Role status.

Posted on 2007-11-14
12
Medium Priority
?
786 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
RHCE - Red Hat OpenStack Prep Course

This course will provide in-depth training so that students who currently hold the EX200 & EX210 certifications can sit for the EX310 exam. Students will learn how to deploy & manage a full Red Hat environment with Ceph block storage, & integrate Ceph into other OpenStack service

 

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 2000 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

801 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