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);
Related
I created a class I named Cashiers(shown below). I can create new instances through code no problem. What I can not do is have a user input a string value into a string variable I named CashierLOgInNName. So if the user inputs the value as DSPR I want to be able to create a new cashier object by that name, or the equivalent of
Cashiers DSPR = new Cashiers();
I've included the parts of my code that pertain to this question. Ideally if I could have the line or lines of code that would enable me to have this work and why that be excellent.
public class Cashiers
{
public int CashierID;
public int Password;
public string FirstName;
public string LastName;
public void SetCashiers(int CashierID, int Password,string FirstName, string LastName )
{
this.CashierID = CashierID;
this.Password = Password;
this.FirstName = FirstName;
this.LastName = LastName;
}
public void SetNewCashier(int CashierID, int Password, string FirstName, string LastName)
{
//Cashiers NewCashier = new Cashiers();
this.CashierID = CashierID;
this.Password = Password;
this.FirstName = FirstName;
this.LastName = LastName;
}
}
Console.WriteLine("enter New Log in name");
string CashierLOgInNName = Console.ReadLine();
To more directly answer with your example, building on the best method of using a dictionary (aka Key Value Pair):
Dictionary<String,Cashiers) dictCashiers = new Dictionary<String,Cashiers>();
Console.WriteLine("Enter new login name:");
String CashierLogInName = Console.ReadLine();
Cashiers newCashier = new Cashiers();
dictCashiers.Add(CashierLogInName,newCashier);
//replace constants in the next line with actual user's data, probably input from more ReadLine queries to user?
dictCashiers[CashierLogInName].SetNewCashier(1,2,"Jane","Doe");
You can see dictCashiers[CashierLogInName] accomplishes what I believe you are looking for, and retrieves the Cashiers object associated with that Login ID.
It sounds to me like what you're really looking for is either a database (which is too broad to answer here) or a dictionary.
In a dictionary, you'll be able to store your Cashier objects keyed by a string. You aren't affecting the name of the variable, of course, but you can still use that name in a theoretical context to get at what you're looking for. If you did actually change the name, that would lead to a need for reflection, which is messy and slow.
private Dictionary<string, Cashiers> dict = new Dictionary<string, Cashiers>();
private void Save(string name, [probably some other details?])
{
dict[name] = new Cashiers(); // or whatever
}
private void Print(string name)
{
Console.WriteLine(dict[name]);
}
private void PrintAll()
{
Console.WriteLine(string.Join(Environment.NewLine, dict.Select(c => c.Key + "\t" + c.Value.ToString()));
}
Obviously my implementation here leaves something to be desired, but it shows how you can use it.
I am trying to create a program that mimics an ATM. In my program, I need to check if the string that a user enters matches the Name property of any objects within a list of objects. If it does not match, then the account is automatically added with some other default values. If it does match, then I need to set the variables that are accessed on another form to the properties of that account object. Additionally, those properties will need to be updated from the other form, so that the object is kept current. I think that I can figure out how to update those properties, but I am having difficulty with trying to set the variables to the current account, more specifically, how to access the properties of the matching account. My class constructor is as follows:
class Account
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private int acctNum = 0;
public int AcctNumber
{
get
{
return acctNum;
}
set
{
acctNum = value;
}
}
//initialize the CheckBalance value to 100.00
private decimal checkBalance = 100.00M;
public decimal CheckBalance
{
get
{
return checkBalance;
}
set
{
checkBalance = value;
}
}
public Account(string Name)
{
this.Name = Name;
}
private decimal saveBalance = 100.00M;
public decimal SaveBalance
{
get
{
return saveBalance;
}
set
{
saveBalance = value;
}
}
}
This works out just fine, as the only constructor that I need is the Name property, while the other properties are automatically set to a base value. The list and relevant code that I currently have are as follows:
//variable that will be used to check textbox1.Text
string stringToCheck;
//array of class Account
List<Account> accounts= new List<Account>();
public MainMenu()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//set value to user's input
stringToCheck = textBox1.Text;
//set a var that only returns a value if the .Name already exists
var matches = accounts.Where(p => p.Name == stringToCheck);
//check through each element of the array
if (!accounts.Any())
{
accounts.Add(new Account(stringToCheck));
}
else if (matches != null)
//set variables in another form. not sure if these are working
Variables1.selectedAccount = ;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = accounts[i].CheckBalance;
//same thing?
Variables1.selectedSaveBalance = accounts[i].SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
this.Hide();
acctMenu.Show();
}
In the above code, the "else if (matches != null)" is more of a filler, since I am not sure what to use. Of course, I also need to re-write the portion "if (!accounts.Any())" because once the list is populated with at least one object, this code will never occur again. So, really, I just need to know how to check for a matching account and how to access the properties of that account so that I can set the Variables1 properties to match. Thanks for any help!
If it works for your particular situation, var account = accounts.FirstOrDefault(p => p.Name == stringToCheck) will give you the first account in the collection that matches the expression or null if nothing exists.
check if account != null to ensure you do not get a null reference exception when trying to get property values.
Then, use account.CheckBalance to get the property value for that particular account.
I may not be fully understanding the question and cannot comment because I do not have a 50 reputation : (
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 have the following code:
private void button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1("ttt");
myClass.Name = "xxx";
MessageBox.Show(myClass.Name);
}
and
class Class1
{
string str = "";
public Class1(string name)
{
str = name;
}
public string Name
{
get { return str; }
set;
}
}
Initially I set:
myClass.Name = "ccc";
but later changed it to:
myClass.Name = "xxx";
and also changed:
set {str = value;}
to:
set;
Why when I run it do I get "ccc" instead of "xxx" ?
In my current code there is "ccc".
public string Name
{
get { return str; }
set;
}
should be
public string Name
{
get { return str; }
set { str = value; }
}
Change your Name property as follows:
public string Name
{
get { return str; }
set { str = value; }
}
To answer your question, the reason why you get "ccc" instead of "xxx" is that you have compile errors. When you run your application it will ask you if you want to run the latest known working configuration. The last time your program did compile, you used "ccc" as literal, and that is what is still running.
Fix the compile errors and run it again, and then it will be "xxx"
The pattern
public string Name {get;set;}
is what is called "Auto-Implemented Properties".
The compilier creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
What you original code seems to be doing is get on a field you defined but a set on the anonymous backing field. Therefore build error ...
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...