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;
}
Related
Model class
using System;
namespace MySystem.Models
{
public class User
{
private string username;
private string age;
public User()
{
}
public User(string username, string age)
{
this.username = username;
this.age = age;
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Age
{
get { return age; }
set { age = value; }
}
}
}
View
#using System.Linq
#model List<MySystem.Models.User>
#using (Html.BeginForm("AddWithHTMLHelperAndModel",
"List<MySystem.Models.User>", FormMethod.Post))
{
if (!Model.Any())
{
<label>Empty</label> // Model is void, why??
#Model.Add(new User("Username1", "35"))// Returns error that void can't be changed to obj.
}
else
{
<label>Model has content.</label>
}
}
Controller
public ActionResult AddWithHTMLHelperAndModel()
{
List<User> usermodel = new List<User>();
return View(usermodel);
}
[HttpPost]
public ActionResult AddWithHTMLHelperAndModel(List<User> user)
{
var updated_model = user;
return View(updated_model);
}
There appears to be an initialisation problem. No idea why. Before I was able to use the related model just with the reference to it in the beginning of the view (no separate initialisation required).
Also, if I try my User model without the view, just in "main", it works as expected. What am I doing wrong?
The issue was with this:
#Model.Add(new User("Username1", "35"))
Resulting in this error message:
Error message
Removing the leading "#" works. The good syntax is:
Model.Add(new User { Username = "I am in the view!", Age = "15"});
I was mislead in believing that my Model was empty, since it seemed to go into the (!Model.Any()) part.
I hope this can save someone 2 Days of frustration...
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 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.
The way I set my code won't let me obtain information from the previous page.
information on page 1:
public string Name{ get { return FirstName.Text; } private set{} }
public string Email { get { return email.Text; } private set { } }
information on page two (to obtain):
Mark up code:
<%# PreviousPageType VirtualPath="~/Registration.aspx" %>
c# code:
protected void Page_Load(object sender, EventArgs e)
{
string name = "";
string email = "";
if (PreviousPage != null)
{
name = PreviousPage.Name;
email = PreviousPage.Email;// both fields are always null... why?
}
I changed my last section to this: still wont work
Response.Redirect("CheckYourEmail.aspx");
}
ViewState["LoginName"] = FirstName.Text;
ViewState["Email"] = email.Text;
ViewState["Password"] = password1.Text;
}
public string Name { get { return ViewState["LoginName"].ToString() ; } private set { } }
public string Email { get { return ViewState["Email"].ToString(); } private set { } }
public string UserPassword { get { return ViewState["Password"].ToString(); } private set { } }
i also tried with Request["Email"];
wont work
Save the values in the session object and get these values from the other page.
// When retrieving an object from session state, cast it to
// the appropriate type.
ArrayList customers = (ArrayList)Session["Customers"];
// Saving into Session to be retrieved later.
Session["Customers"] = customers;
As far as I can see your code looks correct. Do you have viewstate enabled for the textboxes?
When you do a cross page postback the lifecycle of the source page starts over again. As soon as the target page accesses the PreviousPage Property.
Can you get the values through the Request object?
Request["FirsName"]
Http protocol is an state Less Protocol.
Try to use Session or cache to persist data.
The previous page's instance is simply gone, so there's no way to retrieve data from it...
I have a static class in my solution that is basically use a helper/ultility class.
In it I have the following static method:
// Set the user
public static void SetUser(string FirstName, string LastName)
{
User NewUser = new User { Name = String.Format("{0}{1}", FirstName, LastName) };
HttpCookie UserName = new HttpCookie("PressureName") { Value = NewUser.Name, Expires = DateTime.Now.AddMinutes(60) };
}
User is a simple class that contains:
String _name = string.Empty;
public String Name
{
get { return _name; }
set { _name = value; }
}
Everything works up until the point where I try to write the cookie "PressureName" and insert the value in it from NewUser.Name. From stepping through the code it appears that the cookie is never being written.
Am I making an obvious mistake? I'm still very amateur at c# and any help would be greatly appreciated.
Creating the cookie object is not enough to have it sent to the browser. You have to add it to the Response object also.
As you are in a static method, you don't have direct access to the page context and it's Response property. Use the Current property to access the Context of the current page from the static method:
HttpContext.Current.Response.Cookies.Add(UserName);