adding multiple sessions into one (for permission) - c#

this is my code and I've set permissions so if a user id is 132 he/she will see button1, etc. The problem is that I have multiple of these permission throughout the webpage (for other functions) and if I need to add someone I have to change it in 5/6 places rather than one. Can I combine all the sessions into one master session? Also I dont want to create a table in the DB
else if (Session["UserId"].Equals("132") || (Session["UserId"].Equals("210"))
|| (Session["UserId"].Equals("41")) || (Session["UserId"].Equals("103"))
|| (Session["UserId"].Equals("404")) || (Session["UserId"].Equals("130"))
|| (Session["UserId"].Equals("92")) || (Session["UserId"].Equals("490"))
|| (Session["UserId"].Equals("172")))
{
//do something
}

I would create a seperate database table for permissions or add another row to the existing user-table with a boolean to check if the user is valid to see the button.
This is really too much just to check if a user is allowed to see the button or not.
You could also create a list with the userids and check if the current logged in user is in the list, then show the button.
Edit cause of comment to serve some code:
var allowedUserIds = new List<int> {1,2,3,4,5};
var currentUserId = Session["UserId"];
bool isInList = allowedUserIds.IndexOf(currentUserId) != -1;
if(isInList){
...
}

Related

C# - Creating a list by filtering a pre-exisitng list

I am very new to C# lists and databases, please keep this in mind.
I have a list of workouts saved in a database that also has the UserID field to make each workout added to the table unique to each user. I want to make a list view for when the user logs in, they can see only their workouts.
I have tried to do this by creating a new list without all the workouts that don't have that User's primary key/userID
public void Read()
{
using (UserDataContext context = new UserDataContext())
{
DatabaseWorkouts = context.Workouts.ToList(); // Saves the users from the database into a list
// DatabaseWorkouts = context.Workouts.FindAll(item => item.UserID != Globals.primaryKey); I thought this would work
foreach (var item in DatabaseWorkouts.ToList())
{
if (DatabaseWorkouts.Exists(item => item.UserID != Globals.primaryKey))
{
DatabaseWorkouts.Remove(item);
}
}
ItemList.ItemsSource = DatabaseWorkouts; //Displays the list on the listview in the GUI
}
}
I have run many tests with this code above and I think that it only displays the workouts that are most recent and accept conditions, instead of just accepting conditions.
Please help
Instead of fetching all the workouts and then removing the ones that don't belong to the user, you could just directly fetch the user's ones.
Assuming that Globals.primaryKey is the targeted user's id, you can do the following
var userWorkouts = context.Workouts.Where(w => w.UserId == Globals.primaryKey).ToList();
ItemList.ItemsSource = userWorkouts;

Limiting number of logged in users on .NET MVC application

I have done a fair amount of research on how to limit amount of users that can login into an application. Now I've seen people mentioning cookie-based checkups to see how many users are logged into the account but I haven't seen any implementation where I could see how that works exactly.
Besides that I'm wondering if there is already implemented solution of this in .NET MVC 5?
My final goal is following:
Only two users can login on one account
If third user logs in, the first one that logged in should be kicked out of the system automatically
Can someone help me out with this one ?
Best regards
This check sounds similar to Netflix check - you can login using only 5 devices.
But there is limitation on devices - hence different sessions in same login ID can be identified using IP addresses and device information in HTTP packet.
This is very nice code sample.
IsUserLoggedInElsewhere will check the logins from other places.
Instead of log everyone else out you will have to log out the first user based on login time whenever third user logs in using same account.
Please refer this article for more details about this.
public static bool IsYourLoginStillTrue(string userId, string sid)
{
CapWorxQuikCapContext context = new CapWorxQuikCapContext();
IEnumerable<Logins> logins = (from i in context.Logins
where i.LoggedIn == true &&
i.UserId == userId && i.SessionId == sid
select i).AsEnumerable();
return logins.Any();
}
public static bool IsUserLoggedOnElsewhere(string userId, string sid)
{
CapWorxQuikCapContext context = new CapWorxQuikCapContext();
IEnumerable<Logins> logins = (from i in context.Logins
where i.LoggedIn == true &&
i.UserId == userId && i.SessionId != sid
select i).AsEnumerable();
return logins.Any();
}
public static void LogEveryoneElseOut(string userId, string sid)
{
CapWorxQuikCapContext context = new CapWorxQuikCapContext();
IEnumerable<Logins> logins = (from i in context.Logins
where i.LoggedIn == true &&
i.UserId == userId &&
i.SessionId != sid // need to filter by user ID
select i).AsEnumerable();
foreach (Logins item in logins)
{
item.LoggedIn = false;
}
context.SaveChanges();
}
I think it can be done by one of two ways:
1 : by data base
-- Add a field in users table refer to login_status (Bool)- and Last_login_Time (Date)
-- Change login_status to (True) and Last_login_Time to dateTime.now
-- Before login get from Users table number of users with login_status true
-- if count less than two ..normal login
-- if count more than = 2 end session for user with earlier login time and set current user is logged..
2 - Also it can be done by using global variables in Global.asax and

Match Table Header To String inside LINQ

Hi there I have a database of users who are able to receive emails for specific servers.
Table Ex:
UserName Server1 Server2 Server3
Jane.Doe True False True
Let me explain what exactly is happening, so I set a true or false to the server if they can receive emails or not for specific server.
Now a user submits a log and they pick a server they are reporting to. The Admins of that server will get an email.
However I don't want to hard code in (My boss got mad at me):
Example:
if (logSubmission.curServer == "Server1")
{
email = db.Users.Where(m => m.Server1 == true).Select(m => m.UserName).ToList();
}
So what I thought I could do is:
IEnumerable<SelectListItem> server = db.servers.Select(m => new SelectListItem
{
Value = m.server1,
Text = m.server1
});
string serverFixed = "";
foreach (var item in server)
{
if (item.Text == logSubmission.curServer)
{
serverFixed = item.Text;
serverFixed = serverFixed.Replace(" ", string.Empty);
}
}
I had a table called servers which holds all the servers.
So I call that and create a list of SelectListItem.
I take the Text of the server and match it with what the current server we are looking at.
Once That is done I had to remove spaces because some servers were like this: "Server 2"
And since my User Table Has it as "Sever2" I needed to remove spaces to match it.
Now I need to find a way to get that variable serverFixed into a similar look as:
email = db.Users.Where(m => m.Server1 == true).Select(m => m.UserName).ToList();
I feel like if I can change the .Where to somehow match the serverFixed I could do it.
Any ideas what I could do? Thanks!
Your Table is already hard coded. I'm not sure if that was a good decision to use several fields for servers instead of one foreign key field to a catalogue table with all servers. But maybe you had some reasons for it. I believe it's impossible to use some kind of variable for a field in LINQ. So I would propose to create an enum with all servers like
public enum ServerEnum {server1, server2, ...}
and than you can use it to identify your servers:
switch(logSubmission.curServer)
{
case (ServerEnum.Server.ToString()):
email = db.Users.Where(m => m.Server1 == true).Select(m => m.UserName).ToList();
break;
...
}
But anyway if you could change a structure of your tables that would be a better decision.

Retrieve Lotus Notes contact information using contact ID in c#

Im developing a tool that needs to access to the names.nsf database inside IBM Lotus Notes, and, using the lotus contact ID (Employee ID) (this id will be provided by the user), retrieve the full information of the person (Name, Position, Phone #....)
I found an example at Codeproject.com (http://www.codeproject.com/Articles/18517/Lotus-Notes-Integration-with-Microsoft-NET-Platfor), however it takes around 10 minutes to get the information the way the example does it (the database has more or less 5000 entries), so I'm searching for a faster way of doing it (if I actually use Lotus notes for this it takes about a second!).
Is there a way to accomplish this task without having the user waiting for minutes?
Thought that maybe you can help me out with this one.
The sample you are using goes through the view using
NotesViewEntry viewEntry = notesViewCollection.GetNthEntry( rowCount );
This is (one of) the worst methods to use as it goes for every iteration from the top of the view and iterates through all docs until it reached the nth document.
There are two options:
1) Optimize this code by using
NotesViewEntry viewEntry = notesViewCollection.GetFirstEntry();
and at the end
viewEntry = notesViewCollection.GetNextEntry(viewEntry);
2) (in my humble opinion the better way): Change the code:
- you need a view with the first column sorted by your key => contact ID (Employee ID)
- You can the access the ViewEntry by a code like
LotusNotesView.GetEntryByKey( EmployeeID, true);
If you are lucky the names.nsf is full text indexed. If it's not you could try to ask if it could be full text indexed. When it's indexed you can get the person document quicly like this:
LotusNotesView.FTSearch("[EmployeeID]=1234567", 1);
NotesDocument docPerson = LotusNotesView.GetFirstDocument();
The use of GetNthEntry certainly causes some performance issues. I've taken the relevant code from that site and rewrote it to use the GetFirst/GetNext pattern, which is recommended for all view processing in Lotus Notes.
Note this hasn't been tested, of course. The point is to get the first entry in your collection, check that it is an object, and then process it. At the end of the loop, get the next entry and repeat until you hit null.
NotesViewEntryCollection notesViewCollection = LotusNotesView.AllEntries;
NotesViewEntry viewEntry = notesViewCollection.GetFirstEntry();
while (viewEntry != null)
{
//Get the first document of particular entry.
NotesDocument document = viewEntry.Document;
object documentItems = document.Items;
Array itemArray1 = (System.Array)documentItems;
for( int itemCount=0 ; itemCount< itemArray1.Length; itemCount++ )
{
NotesItem notesItem =
(Domino.NotesItem)itemArray1.GetValue( itemCount );
//compare field value with specific value entered by user
if( notesItem.Text !=null )
{
if( (notesItem.Text.ToUpper()).StartsWith( fieldValue ))
{
Contact contact = new Contact();
for( int icount=0 ; icount< itemArray1.Length; icount++ )
{
NotesItem searchedNotesItem =
(Domino.NotesItem)itemArray1.GetValue( icount );
string FieldName = searchedNotesItem.Name.ToString();
//For FirstName
if( searchedNotesItem.Name == "FirstName" )
contact.FirstName= searchedNotesItem.Text;
//For LastName
if( searchedNotesItem.Name == "LastName" )
contact.LastName = searchedNotesItem.Text;
//For Office Phone Number
if( searchedNotesItem.Name == "OfficePhoneNumber" )
contact.OfficePhoneNumber = searchedNotesItem.Text;
if( searchedNotesItem.Name == "InternetAddress" )
contact.EmailId = searchedNotesItem.Text;
}//end for
contactsList.Add( contact );
break;
}//End if
}
}
//Get the nth entry of the selected view according to the iteration.
NotesViewEntry viewEntry = notesViewCollection.GetNextEntry(viewEntry);
}
Why are you asking the user to provide his Employee ID? You should ask him to provide his Notes username (either FullName or ShortName), or his email address. Any of those can be looked up very quickly in the $Users view in names.nsf, giving you fast access to the document containing all the data that you need.
Note: I'm aware that some companies actually enter their Employee ID into the ShortName field in names.nsf. If that's the case for your organization, then what you should be doing is opening a NotesView object using the NotesDatabase.getView() method, and then use the NotesView.getDocumentByKey() method to get the document for the user. E.g., something like this:
NotesView usersView = namesDb.getView("$Users");
NotesDocument userDoc = usersView.getDocumentByKey(employeeId);
Then just read the data that you want, using userDoc.getItemValue() for each information field that you are interested in. You should only do a loop through the entire userdoc.Items array if you are really trying to capture everything, including a bunch of internal-use values.

DNN Check if User is in Role Group

I'm adding onto my DNN module a check to exclude certain users from having to answer some questions when logging in. Instead of hard coding each individual role I'd like to instead just exclude anyone within a particular role group. That way if we have more roles in the future we can just add them into the role group if we want them to be excluded.
However, I don't know how you check if a user is in role group. I know how to check the role, but not the group if they are in one.
SOLUTION: Here's the code I put together based on the answers I got. Should work.
RoleGroupInfo RoleGrp = RoleController.GetRoleGroupByName(this.PortalId, "Role Group");
bool bShouldSkipQuestions = false;
if (RoleGrp != null)
{
Dictionary<string, RoleInfo> GroupChk = RoleGrp.Roles;
if (GroupChk.Count > 0)
{
foreach (var item in GroupChk.Values)
{
if (_user.IsInRole(item.RoleName))
{
bShouldSkipQuestions = true;
break;
}
}
}
}
Role groups aren't really intended to be used like that (they're intended just for end-user organization), so there isn't a direct way to check that. You'll want to get all of the roles in the group (RoleController.GetRolesByRoleGroup) and then check PortalSecurity.IsInRoles, passing in a comma-separated string of the role names.
Try this code:
var roleGroup = RoleController.GetRoleGroupByName(this.PortalId, "Role Group");
var shouldSkipQuestions = roleGroup != null
&& roleGroup.Roles.Keys.Any(role => _user.IsInRole(role));

Categories

Resources