473,839 Members | 1,358 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to enable/disable controls against a user's permission via Type Casting

33 New Member
I want to enable/disable controls of a asp.net page against a logged in user's permission. say 'admin' & 'hr' can change user's birth date text-box in a page but others will see the text-box as disabled.

so i wrote a function like this
Expand|Select|Wrap|Line Numbers
  1. [Flags]
  2.     public enum UserRoles
  3.     {
  4.         GroupLead = 0x2,
  5.         WebAdmin = 0x4,
  6.         Developers = 0x8,
  7.         Hr = 0x10,
  8.         Accounts = 0x20,
  9.         ItInfra= 0x40
  10.     }
  12.     public static class UserPermission
  13.     {
  14.         public static bool IsPorpertySupport(int empId, UserRoles[] uRoles)
  15.         {
  16.             // inner logics to return true or false acc. as the user is in the specified roles(s) or not.
  17.         }
  18.     }
And from page i'll call it like this

Expand|Select|Wrap|Line Numbers
  1. tblAddGrInfo.Visible = UserPermission.IsPorpertySupport(Convert.ToInt16(User.Identity.Name),new[] {UserRoles.Hr, UserRoles.WebAdmin});
But now for many controls (like a textbox, a dropdownlist, a label, a grid etc.) in the page i thought of a function like

Expand|Select|Wrap|Line Numbers
  1. public static bool SetEnable(int empId,  System.Web.UI.Control[] ctrlCol, UserRoles uRole)
  2. {
  3.      try
  4.      {
  5.         foreach (var c in ctrlCol)
  6.            c.Enabled = IsPorpertySupport(empId, new [] {uRole}); // ERROR LINE
  7.         return true;
  8.       }
  9.       catch (Exception)
  10.       {
  11.          return false;
  12.       }
  13. }
But the problem is a control don't have Enabled property... you have to cast it to its proper type...
My question is how do i do that? Writing cases for each control (textbox, dropdownlist, grid, checkbox, radiobutton etc) is hard to do... Is there a shorter way?

Currently i'm using it in page load like
Expand|Select|Wrap|Line Numbers
  1. var isUserHr = UserPermission.IsPorpertySupport(Convert.ToInt16(User.Identity.Name), new[] { UserRoles.Hr });
  2. txtEmployeeDOB.Enabled = isUserHr; //TextBox
  3. txtEmployeePANNo.Enabled = isUserHr;
  4. txtEmployeePassportNo.Enabled = isUserHr;
  5. txtEmployeeFirstName.Enabled = isUserHr;
  6. txtEmployeeLastName.Enabled = isUserHr;
  7. txtEmployeeBankAccNo.Enabled = isUserHr;
  8. txtEmployeePFAccNo.Enabled = isUserHr;
  9. chkIsEmployeeActive.Enabled = isUserHr; //CheckBox
  10. ddlPaysleepDesg.Enabled = isUserHr; //DropDownList
  11. ddlWorkingDesg.Enabled = isUserHr; //DropDownList
but if control increases it's going to be difficult...
Jun 2 '10 #1
3 3204
9,735 Recognized Expert Moderator Expert
If I were you I would use Reflection.

First thing you need to do is import the Reflection namespace:
Expand|Select|Wrap|Line Numbers
  1. using System.Reflection;
Then you need to use reflection to retrieve all the properties of the control (Enabled is a property). To retrieve the properties for the control you will use the Control's Type and call the GetProperties() method. This method returns an array of PropertyInfo types. Once you have this array, you need to retrieve the PropertyInfo type that represents the Enabled property (if there is one). If you are able to retrieve the Enabled-PropertyInfo type then you can use it to set the value for your control.

See the comments in the code for a more detailed explanation:
Expand|Select|Wrap|Line Numbers
  1. //retrieving whether or not the control should be enabled
  2. bool isUserHr = UserPermission.IsPorpertySupport(Convert.ToInt16(User.Identity.Name), new[] { UserRoles.Hr });
  4. //looping through each control 
  5. foreach (var ctrl in ctrlCol)
  6. {
  7.   //grabbing all of the properties for the control
  8.   PropertyInfo[] properties = ctrl.GetType().GetProperties();
  10.   //attempting to retrieve the Enabled property for the control
  11.   PropertyInfo enabledProperty = Array.Find(properties, (pi) => string.Compare(pi.Name, "Enabled", true) == 0);
  13.   //checking whether or not there was an Enabled property
  14.   if (enabledProperty != null)
  15.   {
  16.     //if there is an enabled property, setting the
  17.     //control's enabled property to the isUserHr 
  18.     //which indicates whether or not the control should 
  19.     //be enabled
  20.     enabledProperty.SetValue(ctrl, isUserHr, null);
  21.   }
  22. }
Jun 2 '10 #2
33 New Member
Thanks Mate... that was perfect ....
Jun 3 '10 #3
9,735 Recognized Expert Moderator Expert
:) Glad I could help :)
Jun 3 '10 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

by: maxim vexler | last post by:
in a book i am ready now : O'Reilly - Web Database Application with PHP and MySQL, 2nd ed. by David Lane, Hugh E. Williams on chapter 9 the author give an example for age validation : (simplified code, not a direct quote) $dob = mktime(0,0,0, 5, 3, 1983); if ((float)$dob > (float)strtotime("-18years")) {
by: Suzanne Vogel | last post by:
** Isn't the 'static_cast' operator the same as traditional type casting? ie, Aren't the following ways of getting b1, b2 the same? // 'Derived' is derived from 'Base' Derived* d = new Derived(); Base* b1 = static_cast<Base*>(d); Base* b2 = (Base*)d; // traditional type casting Such is my understanding from code samples, my own uses, and this: http://www.cplusplus.com/doc/tutorial/tut5-4.html
by: JohnK | last post by:
under the covers is type casting in VB.Net the same as C# ? myObject = CType(..,..) in VB.Net vs myObject = (SomeClass)aObject
by: chook | last post by:
Wherein differences between type casting in C++ : static_cast, dinamic_cast, reinterpret_cast, const_cast and C type casting, like xxx = (type)yyy; What, when and why is necessary to use?
by: Roman Mashak | last post by:
Hello, All! Given the sample piece of code I have: #include <stdio.h> #include <string.h> int main(void) { short int i, j;
by: Wayne M J | last post by:
I have worked out most type casting and the likes but I am curious about one aspect. Endpoint ep...; IPEndPoint iep...; .... ep = (EndPoint)iep; .... iep = (IPEndPoint)ep; ....
by: René Nordby | last post by:
Hi there, Is there anyone that knows how to do the following? I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than the Inherit statement).
by: Enekajmer | last post by:
Hi, 1 int main() 2 { 3 float a = 17.5; 4 printf("%d\n", a); 5 printf("%d\n", *(int *)&a); 6 return 0; 7 }
by: Ben R. | last post by:
How does automatic type casting happen in vb.net? I notice that databinder.eval "uses reflectoin" to find out the type it's dealing with. Does vb.net do the same thing behind the scenes when an invisible cast is made? Is there any reason why one would use databinder.eval while in VB.NET? I can see why one might use it in C# so as to avoid specifying the type for the cast but since this is not necessary in VB.NET, I'm not sure I follow. ...
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? class Derived (Base): def __init__ (self, base_object): # ( copy all attributes ) ...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.