I need some help here, I am trying to identify a user after they have logged in. My code works ok apart from the where clause.
How do you identify a user, I am basically trying to say where UserName == loginName give me the full record.
Then from the record I can pull out the GarageID, any help or pointers much appreciated.
private void FindGarageID()
{
System.Security.Principal.WindowsIdentity identity = Context.Request.LogonUserIdentity;
string loginName = identity.Name;
using (tyrescannerdatabaseEntities dbcontext = new tyrescannerdatabaseEntities())
{
garage = (from r in dbcontext.AspNetUsers
where r.UserName == loginName
select r).FirstOrDefault();
if (!garage.GarageID.Equals(null))
{
garageID = (int)garage.GarageID;
}
else
{
garageID = 1;
}
}
So here is how I would do this. I would create a static class called Session. This just encapsulates the accessing of session variables for me.
public static class Session
{
public static string UserName
{
get { return (JsonWhereClause)HttpContext.Current.Session["UserName"]; }
set { HttpContext.Current.Session["UserName"] = value; }
}
}
Then when the user logs in, I would do this.
Session.UserName = ""//User inputed username
This would then make your code be this.
private void FindGarageID()
{
string loginName = Session.UserName;
using (tyrescannerdatabaseEntities dbcontext = new tyrescannerdatabaseEntities())
{
garage = (from r in dbcontext.AspNetUsers
where r.UserName == loginName
select r).FirstOrDefault();
if (!garage.GarageID.Equals(null))
{
garageID = (int)garage.GarageID;
}
else
{
garageID = 1;
}
}
Note that the Session will only be available on the webserver, so if you have a service you would need to pass the username to the service.
Related
I am authenticated using active directory . I am successfully authenticate using
Membership.ValidateUser(login.UserName, login.Password)
method and getting user details from active directory using
Membership.GetUser(login.UserName) but I cant get the country name how can i get the country name or code from AD anyone please help
The country is not a Property by default in MembershipUser , unless you manually specified them in your profile provider.
U have got to use the System.Web.Profile.ProfileBase class .
Here a greate class from #Sky Sanders which also uses the Membership class
public class UserProfile : ProfileBase
{
public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}
public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
[SettingsAllowAnonymous(false)]
public string CountryCode
{
get { return base["countryCode"] as string; }
set { base["countryCode"] = value; }
}
[SettingsAllowAnonymous(false)]
public string Description
{
get { return base["Description"] as string; }
set { base["Description"] = value; }
}
[SettingsAllowAnonymous(false)]
public string Location
{
get { return base["Location"] as string; }
set { base["Location"] = value; }
}
[SettingsAllowAnonymous(false)]
public string FavoriteMovie
{
get { return base["FavoriteMovie"] as string; }
set { base["FavoriteMovie"] = value; }
}
}
Here are some helpful links
How to assign Profile values?
How can i use Profilebase class?
Hope it helps.
I got the answer from LDAP - Retrieve a list of all attributes/values?,
PrincipalContext ctx = new PrincipalContext(
ContextType.Domain,
ConfigurationManager.AppSettings["ADDomainName"],
ConfigurationManager.AppSettings["ADContainer"],
ConfigurationManager.AppSettings["ADUserName"],
ConfigurationManager.AppSettings["ADPassword"]);
UserPrincipal users = UserPrincipal.FindByIdentity(ctx, user.UserName);
DirectoryEntry entry = users.GetUnderlyingObject() as DirectoryEntry;
PropertyCollection props = entry.Properties;
if (entry.Properties["countryCode"].Value != null)
{
user.CountryCode = entry.Properties["countryCode"].Value.ToString();
}
It may helps anyone..
Although it is very late, but the tutorial at following link can really help
How to get User Data from the Active Directory
I have some code that sets up a user:
const string name = "joe";
const string password = "abc";
const string roleName = "def";
After this there is a lot of C# code to add the user:
var role = RoleManager.FindByName(roleName);
if (role == null) {
role = new IdentityRole(roleName);
var roleresult = RoleManager.Create(role);
}
var user = UserManager.FindByName(name);
if (user == null) {
user = new ApplicationUser { UserName = name, Email = name };
var result = UserManager.Create(user, password);
result = UserManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = UserManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name)) {
var result = UserManager.AddToRole(user.Id, role.Name);
}
What I need is to add four or five different users.
Is there a way I can put my users in an object and loop through this calling the adding code ?
There certainly is a way! But to do it properly, it will take a few steps to get there. First, create a small class to represent a "user". Here's one with a constructor and some auto-properties:
public class MyUser
{
public MyUser(string name, string password, string roleName)
{
this.Name = name;
this.Password = password;
this.RoleName = roleName;
}
public string Name { get; set; }
public string Password { get; private set; }
public string RoleName { get; set; }
}
Disclaimer: Don't call this class MyUser, come up with a much better name! This is for illustration only!
Now, to put your users "in an object", you can create a List<T> object and add some new MyUser instances to it:
var newUsers = new List<MyUser>
{
new MyUser("name1", "pwd1", "role1"),
new MyUser("name2", "pwd2", "role2"),
etc.
};
This creates the list and immediately adds the users to it using collection initializer syntax. You can also do it the long way if you need to do it in a loop:
var newUsers = new List<MyUser>();
newUsers.Add(new MyUser("name1", "pwd1", "role1"));
newUsers.Add(new MyUser("name2", "pwd2", "role2"));
// etc.
Next, having your "create user" code in a function will help, but in one that takes a MyUser class as a parameter:
public void CreateUser(MyUser myUser)
{
// A little protection
if (myUser == null)
throw new ArgumentNullException("user");
var role = RoleManager.FindByName(myUser.RoleName);
if (role == null) {
role = new IdentityRole(myUser.RoleName);
var roleresult = RoleManager.Create(role);
}
var user = UserManager.FindByName(myUser.Name);
if (user == null) {
user = new ApplicationUser { UserName = myUser.Name, Email = myUser.Name };
var result = UserManager.Create(user, myUser.Password);
result = UserManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = UserManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name)) {
var result = UserManager.AddToRole(user.Id, role.Name);
}
}
Now, to finally create the users, you just have to loop through your list of MyUsers and pass them over to the CreateUser() function:
foreach (var user in newUsers)
{
CreateUser(user);
}
Of course, you'll want to incorporate try/catch blocks where necessary, add proper validation, etc. This is just to illustrate how I would approach this.
I have a class named "admin" in my asp.net C# project.
It is:
public class Admin
{
private int ID;
private string FirstName, LastName, IsMainAdmin, Email, Username,
Password,BirthDate, EntryDate;
public int id
{
get { return ID; }
set { ID = value; }
}
public string firstname
{
get { return FirstName; }
set { FirstName = value; }
}
public string lastname
{
get { return LastName; }
set { LastName = value; }
}
.
.
.
After login a session is created like this:
Admin admin = isAdmin(username, password);
if (admin != null)
{
**Session.Add("maskanAdmin", admin);**
Response.Redirect("panel.aspx");
}
In other page i need to get admin's ID from session in code behind section after page request via jquery ajax.
Please notice that my code behind Method is [WebMethod] that is not supporting Session Object.
Can i get it? How?
var adminObj = (Admin)Session["maskanAdmin"];
if(adminObj != null)
{
var id = adminObj.id;
var fname = adminObj.firstname;
}
Read more about Read Values from Session State
Update
I am not sure why the question is updated after one hour saying you are using the code in web methods.
However, have a look at Using ASP.NET Session State in a Web Service
You just need to cast it back to an Admin type object when you retrieve it from the Session:
Admin admin = (Admin)Session["maskanAdmin"];
Then you can use the properties of the object as normal:
if(admin.ID == someOtherID)
{
// do stuff
}
Admin variableName = (Admin)Session["maskanAdmin"];
var adminObj = Session["maskanAdmin"];
if(adminObj != null)
{
var admin = (Admin)adminObj;
}
i want to store the login information {id,bagian} so i created Session.cs class.
here is the Session.cs code
class Session
{
public Session ()
{
}
public int idnya { get; set; }
public string bagiannya { get; set; }
public void saveSession(int id, string bagian)
{
idnya = id;
bagiannya = bagian;
}
public void destroySession()
{
idnya = 0;
bagiannya = "";
}
}
so the id will be generated automatically in the following form. however, why does the id return 0 ?
here is my Tambah constructor
public Tambah()
{
InitializeComponent();
textBox2.Text = session.idnya.ToString();
}
here is my Login code. iam using saveSession() method to store the id and bagian into Session.cs class
int nomornya = int.Parse(textBox1.Text);
string passwordnya = textBox2.Text;
string bagiannya = comboBox1.Text;
var data = from a in de.karyawan
where a.nomor_karyawan == nomornya &&
a.password == passwordnya &&
a.bagian == bagiannya
select a;
if (data.Any())
{
if (bagiannya.Equals("Admin"))
{
cmd.cetakSukses("Login sebagai admin", "Login");
loginAdmin();
}
else
{
cmd.cetakSukses("Login sebagai teller", "Login");
loginTeller();
}
main.Show();
this.Hide();
session.saveSession(nomornya, bagiannya);
//MessageBox.Show(session.idnya.ToString());
}
else
{
cmd.cetakGagal("Username atau password salah", "Login");
}
when i call the idnya and bagiannya value, they show the expected values. but, it went wrong when i call the Tambah form.
how to resolve this ?
or is there any alternative way without generating Session class manually ?
any help will be apprciated. thanks !
From the picture and the fact that you suggest that the code doesn't crash I guess that "textBox1" is the second TextBox control in the picture. This control contains text "0", so after you parse this text into an integer it will give you 0. After that, you don't modify this variable ("nomornya" whatever this means), so how do you expect it no to be 0? Besides all this, your question is cluttered and unclear.
EDIT: it is still unclear what do you expect to happen and why. What's the scenario? If the ID comes from the user, how is anyone suppose to guess what are you typing into the textBox1 what produces the unwanted results? When does the "id return 0" as you've stated?
I keep getting a null exception at the ; below. The ApiUsername & ApiPassword have values so I don't undestand if I just set this up wrong or what. The Credentials property is a certain type which has the Username and Password properties that need to be set.
So I have the auto-propery defined:
public CustomSecurityHeaderType SoapCallCredentials { get; private set; }
Then whenever this is hit, I get a null exception and can't figure out why.
private void SetApiCredentials()
{
SoapCallCredentials = new CustomSecurityHeaderType
{
Credentials =
{
Username = PayPalConfig.CurrentConfiguration.ApiUserName,
Password = PayPalConfig.CurrentConfiguration.ApiPassword
}
};
UrlEndPoint = PayPalConfig.CurrentConfiguration.ExpressCheckoutSoapApiEndPoint;
}
I am thinking you need a new....
Credentials = new WhatEverThisTypeIs()
{
Username = PayPalConfig.CurrentConfiguration.ApiUserName,
Password = PayPalConfig.CurrentConfiguration.ApiPassword
}
From the eBay API Example
Credentials needs to be instantiated first, like:
Credentials = new UserIdPasswordType()