TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Pirjo Ahvenainen
NA
4
464
How to choose a class whose method to call
Oct 27 2020 1:48 AM
Hi all,
I would appreciate a hand in designing my code. So far I haven't found a way to do this.
I have a number of classes for different entities (currently 7 but there can be more in the future). I need a method in each of these classes that authorizes user's access to a file resource. Implementation varies but an exception must be thrown if user does not have access to the file in question.
Problem is, when a file is being accessed, I need to call the authorization method of the correct class based on the data on the file. Files are stored in a db table and one of the fields in that table determines which entity the file is related to and how to find which user has access to the file.
So I must read the file data from db, then see which entity it's related to and then call the authorization method of the correct class.
Is there a way in C# to accomplish this without having to make a switch case structure on the file field value?
Example of the classes used:
public
class
FileAttachment
{
// other FileAttachment class stuff
protected
void
AuthorizeFileAccess(FileAttachmentData file)
{
// file has a field which tells which entity it relates to
// here I need to choose which class to use based on the file data
}
}
// simplified example of a related entity
public
class
ChatMessage
{
public
int
SenderUserId;
public
int
RecipientUserId;
// here I need a method that checks that chat message sender's or recipient's
// user id matches the user id of the logged in user
// if not, throw exception
}
And
this
is
what I want to avoid:
switch
(file.SourceValue)
{
case
"ChatMessageAttachmentFile"
:
var cm =
new
ChatMessage();
cm.AuthorizeAttachmentAccess();
case
"OtherAttachmentFile"
:
var other =
new
SomeOtherClass();
other.AuthorizeAttachmentAccess();
default
:
throw
new
Exception(
"Access denied"
);
}
Reply
Answers (
2
)
C# Infix to Postfix Conversion of Multi Digits?
How to check how much memory is used by class or struct object in C#