Solved

Show or Hide a field based on Role status.

Posted on 2007-11-14
12
765 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:quest_capital
Comment Utility
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
Comment Utility
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
Comment Utility
Ah yes you are right

It is User.IsinRole

What I posted before gets the machine role, User.IsinRole gets the asp role
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 22

Expert Comment

by:RedKelvin
Comment Utility
0
 

Author Comment

by:quest_capital
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
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…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

728 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

12 Experts available now in Live!

Get 1:1 Help Now