I have tried to manage user session, but the issue is I can not access other attributes in the database as they are not in the object.
Teacher t = new Teacher
{
t_email = textBox_Login_Email.Text,
t_password = textBox_Login_Pass.Text,
};
Other attributes are t_id and t_name. I can only access these two using the following code
session.Instance.user.t_email
session.Instance.user.t_password
I need to get Teacher's id which is t_id from the database.
I am storing the object "t" in the session object using
session.Instance.user = t;
Below is the code for my session class and login class
session.cs
public class session
{
#region Define as Singleton
private static session _Instance;
public static session Instance
{
get
{
if(_Instance == null)
{
_Instance = new session();
}
return (_Instance);
}
}
private session()
{
}
#endregion
public Teacher user { get; set; }
public bool isLoggedIn
{
get
{
if (user != null)
return true;
else return false;
}
}
}
login.cs
namespace TestBoardAdmin
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void button_Login_Click(object sender, EventArgs e)
{
using (examEntities obj = new examEntities())
{
Teacher t = new Teacher
{
t_email = textBox_Login_Email.Text,
t_password = textBox_Login_Pass.Text,
};
//var x = obj.Teachers.Where(a => a.t_email == t.t_email).Select(a => new { a.t_id });
var y = obj.Teachers.Where(a => a.t_email == t.t_email && a.t_password == t.t_password);
if (y.Count() > 0)
{
MessageBox.Show("Logged In succesfully");
textBox_Login_Email.Clear();
textBox_Login_Pass.Clear();
//this.Close();
session.Instance.user = t;
Chose_Action chose_action = new Chose_Action();
chose_action.Show();
//return 1;
}
else
{
//ViewBag.SuccessMessage = "Wrong Email or Password";
//return 0;
MessageBox.Show("Email or Password Incorrect");
//textBox_Login_Email.Clear();
textBox_Login_Pass.Clear();
}
}
}
private void textBox_Login_Email_TextChanged(object sender, EventArgs e)
{
}
private void textBox_Login_Pass_TextChanged(object sender, EventArgs e)
{
}
}
}
I actually want to store the corresponding t_id in another table when the user adds in the database, the database will also add the id of the user who added something in the database. So, for that I want to get t_id of the corresponding user session.
I have used ado.net and Linq in this project.
Related
I've created Session Variables as Objects from the tutorial http://www.c-sharpcorner.com/uploadfile/9505ae/session-variables-as-objects/
I have given the values of the session from login page LoginUser.aspx .
I am trying to check if the session values are empty or not in Base Page. When I login from the login page and redirects to another page, the session values are checked in base page. The session values in Base page are always NULL. I can not retrieve the session values set from LoginUser.aspx in Base page class.
public class C_UserSession
{
#region Variables
private const string mySessionName = "_MyUserInfo_"; //Our session name
private string username;
private string role;
private string name;
#endregion
#region constructor
public C_UserSession()
{
}
#endregion
#region Public Methods
public string UserName
{
get { return this.username; }
set { this.username = value; Save(); }
}
public string Role
{
get { return this.role; }
set { this.role = value; Save(); }
}
public string Name
{
get { return this.name; }
set { this.name = value; Save(); }
}
#endregion
#region Private Methods
private void CheckExisting()
{
if (HttpContext.Current.Session[mySessionName] == null)
{
//Save this instance to the session
HttpContext.Current.Session[mySessionName] = this;
UserName = string.Empty;
Role = string.Empty;
Name = string.Empty;
}
else
{
//Initialize our object based on existing session
C_UserSession oInfo = (C_UserSession)HttpContext.Current.Session[mySessionName];
this.UserName = oInfo.UserName;
this.Name = oInfo.Name;
this.Role = oInfo.Role;
oInfo = null;
}
}
private void Save()
{
//Save our object to the session
HttpContext.Current.Session[mySessionName] = this;
}
#endregion
}
login page code behind logic
public partial class LoginUser : System.Web.UI.Page
{
C_UserSession usersession;
protected void Page_Load(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
usersession = new C_UserSession();
}
protected void btnSignIn_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = new C_User().Get_LoginUser(inputUserName.Value, inputPwd.Value);
if (dt == null || dt.Rows.Count == 0)
{
Response.Redirect("LoginUser.aspx", false);
return;
}
DataRow dr = dt.Rows[0];
usersession.UserName = dr["USERNAME"].ToString();
usersession.Name = dr["NAME"].ToString();
usersession.Role = dr["ROLE"].ToString();
Int16 userRole = Convert.ToInt16(usersession.Role);
Dictionary<int, string> _redirects = new Dictionary<int, string>
{
{ 1, "product.aspx"}, {2, "shift.aspx" }
};
Response.Redirect(_redirects[userRole], false);
}
}
base page code behind
public class BasePage : System.Web.UI.Page
{
C_UserSession usersession;
public BasePage() {
usersession = new C_UserSession();
}
protected override void OnInit(EventArgs e)
{
try
{
if ( string.IsNullOrEmpty(usersession.UserName) || string.IsNullOrEmpty(usersession.Role))
{
Response.Redirect("LoginUser.aspx");
Context.ApplicationInstance.CompleteRequest();
}
}
catch (Exception ex)
{
throw;
}
}
}
product page inherits Base Page
public partial class product : BasePage
{
// code blocks
}
When I open my product.aspx page, it redirects me to LoginUser.aspx because session values are null. But after providing valid username and password also, I can not go the respective pages. I can not check the session values from Base Page. I can not understand what is the correct approach to do this. Please help. Thank You!!!
Here is the issue. In your BasePage you have this code:
public class BasePage : System.Web.UI.Page
{
C_UserSession usersession;
public BasePage()
{
usersession = new C_UserSession();
}
protected override void OnInit(EventArgs e)
{
try
{
if (string.IsNullOrEmpty(usersession.UserName) || string.IsNullOrEmpty(usersession.Role))
{
}
}
}
}
But off course usersession.Userame will be empty because you just created it in the constructor.
What you should be doing is checking the session to see if it is there and if not, then do a redirect:
public class BasePage : System.Web.UI.Page
{
C_UserSession usersession;
public BasePage()
{
usersession = (C_UserSession)HttpContext.Current.Session[mySessionName];
}
protected override void OnInit(EventArgs e)
{
try
{
if (usersession == null)
{
Response.Redirect("LoginUser.aspx");
Context.ApplicationInstance.CompleteRequest();
}
}
}
}
Now you may have other issues in your code but that is the answer to your question.
Please do yourself a favor: If you are coding in C# then follow the C# coding conventions. Stop using names like C_UserSession and call it something without the underscore such. Do not call your class product but call it Product (Pascal Notation) or better yet call it ProductPage. Take some time and study your code and clean it up.
I don't think you are ever initializing your user object. You have a CheckExisting() private method on your class which appears to re-hydrate the class from session if it's there, but this is never called. If you don't call this within your class then it won't fill those properties and they will always be the default.
I have an UWP app which has two pages HomePage and EditItemPage. On HomePage I created a button which navigates to EditItemPage passing class NavigationContext which bool isNewItem = true. Then, I create new Item on EditItemPage, user changes some info and clicks button Save. That button passes that created Item in NavigationContext to HomePage. The problem is when I click on back button without clicking Save button my HomePage somehow get that item.
EditItemPage.xaml.cs
public sealed partial class EditItemPage : Page
{
public EditItemPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
ViewModel.CleanNavigationBackStack.Execute(e.Uri);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is NavigationContext)
{
var context = (NavigationContext) e.Parameter;
if (context.ContextType == NavigationContextType.ShareOperation)
{
ViewModel.HandleNewUri.Execute(context.ShareOperation);
}
else if (context.ContextType == NavigationContextType.FeedItem)
{
if (context.IsNewItem)
ViewModel.HandleNewFeedItem();
else
{
ViewModel.HandleExistingFeedItem(context.FeedItem);
}
}
else
throw new ArgumentOutOfRangeException();
}
}
private EditItemViewModel ViewModel => this.DataContext as EditItemViewModel;
}
HomePage.xaml.cs
public sealed partial class HomePage : Page
{
public HomePage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter is NavigationContext)
{
var context = (NavigationContext) e.Parameter;
if (context.ContextType == NavigationContextType.FeedItem)
{
if (context.IsNewItem)
ViewModel.HandleNewFeedItem(context.FeedItem);
}
else
throw new ArgumentOutOfRangeException();
}
}
private FeedViewModel ViewModel => this.DataContext as FeedViewModel;
}
NavigationService:
public class NavigationService : INavigationService
{
private readonly Dictionary<string, Type> _pagesDictionary;
private Frame _mainFrame;
public const string UnknownPageKey = "-- UNKNOWN --";
public NavigationService()
{
_pagesDictionary = new Dictionary<string, Type>();
}
public void Configure(string key, Type pageType)
{
if (key == null || pageType == null) return;
Type value;
if (_pagesDictionary.TryGetValue(key, out value))
{
if (value != pageType)
{
throw new Exception(
$"Attempt to add a page of type '{pageType}' to already existing pair of '{key}:{value}'. Consider another string.");
}
}
else
{
_pagesDictionary.Add(key, pageType);
}
}
public void GoBack()
{
if (EnsureMainFrame() && _mainFrame.CanGoBack)
_mainFrame.GoBack();
}
public void NavigateTo(string pageKey)
{
if (pageKey == null) return;
Type page;
if (_pagesDictionary.TryGetValue(pageKey, out page))
{
if (EnsureMainFrame())
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
AppViewBackButtonVisibility.Visible;
_mainFrame.Navigate(page, null,
new Windows.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
}
}
else
{
throw new Exception($"There is no page associated with string '{pageKey}'.");
}
}
public void NavigateTo(string pageKey, NavigationContext context)
{
if (pageKey == null) return;
Type page;
if (_pagesDictionary.TryGetValue(pageKey, out page))
{
if (EnsureMainFrame())
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
AppViewBackButtonVisibility.Visible;
_mainFrame.Navigate(page, context,
new Windows.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
}
}
else
{
throw new Exception($"There is no page associated with string '{pageKey}'.");
}
}
private bool EnsureMainFrame()
{
if (_mainFrame != null) return true;
var appShell = Window.Current.Content as AppShell;
if (appShell != null) _mainFrame = appShell.AppFrame;
return _mainFrame != null;
}
public string CurrentPageKey
{
get
{
string key;
try
{
key = _pagesDictionary.FirstOrDefault(x => x.Value == _mainFrame.CurrentSourcePageType).Key;
}
catch (NullReferenceException)
{
return UnknownPageKey;
}
return key;
}
}
public void RemoveLast()
{
if (EnsureMainFrame() && _mainFrame.CanGoBack)
{
_mainFrame.BackStack.RemoveAt(_mainFrame.BackStackDepth - 1);
}
}
}
I've read that GoBack() doesn't pass any argument but when I click it method OnNavigatedFrom somehow get that old NavigationContext. Tell me when I make a mistake :)
I have a login form in the MainWindow of my WPF application. If the user logs in successfully, I want to open the HomeWindow. My problem is that I need to pass the adminID variable from the MainWindow to the HomeWindow. How can I do this?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
int errors = 0;
if (txtUsername.Text == "")
{
lblUsernameStatus.Content = "This field is required.";
errors = errors + 1;
}
if (txtPassword.Text == "")
{
lblPasswordStatus.Content = "This field is required.";
errors = errors + 1;
}
if (errors == 0)
{
Administrator TryLogin = new Administrator();
if (TryLogin.VerifyUser(txtUsername.Text, txtPassword.Text))
{
HomeWindow home = new HomeWindow();
int adminID = TryLogin.userID;
home.Show();
this.Close();
}
else
{
lblLoginStatus.Content = TryLogin.status;
}
}
}
PS: I haven't written anything in the HomeWindow.xaml.cs file.
Define an initializer in HomeWindow to accept the data you wish to send:
private int AdminID;
public HomeWindow()
{
InitializeComponent();
}
public HomeWindow(int adminID) : base()
{
AdminID = adminID;
}
Then you can just:
HomeWindow home = new HomeWindow(TryLogin.userID);
home.Show();
this.Close();
Declaring static variable would be the simplest and easiest way because once login is authorized, the value doesn't change until logged off(application is exited)
I also used a way of passing value through Window constructor but static variables are much easier to utilize many fixed data of the logged-in users like customized setting data for each users. I also have a WPF app and pass 11 values and utilize easiily everywhere inside application.
Declare as static variable in MainWindow like,
public static int adminID;
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
adminID= TryLogin.userID;
}
And usage in HomeWindow is like,
MainWindow.adminID
Hope this helps..
There are different ways to achieve this.
Here is an example using singleton
public class User
{
private static readonly User _instance;
private static object syncRoot = new Object();
public string Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string SomeOtherProperty { get; set; }
private User()
{
// Initialize defaults
}
public void Reset()
{
// Clear existing values
}
public static User Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new User();
return _instance;
}
}
}
}
}
On your login form:
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
int errors = 0;
if (txtUsername.Text == "")
{
lblUsernameStatus.Content = "This field is required.";
errors = errors + 1;
}
if (txtPassword.Text == "")
{
lblPasswordStatus.Content = "This field is required.";
errors = errors + 1;
}
if (errors == 0)
{
Administrator TryLogin = new Administrator();
if (TryLogin.VerifyUser(txtUsername.Text, txtPassword.Text))
{
User.Instance.Reset(); // Make sure old data is removed
User.Instance.Username = txtUsername.Text;
User.Instance.Password = txtPassword.Text;
HomeWindow home = new HomeWindow();
int adminID = TryLogin.userID;
home.Show();
this.Close();
}
else
{
lblLoginStatus.Content = TryLogin.status;
}
}
}
On your home form:
You can retrieve the User credentials using User.Instance just make sure you reset it on logoff.
Using C# 5.0, I'm creating a publish/subscribe relationship on a static field, so that I can access it from multiple pages. In the host window, I have
public enum PLCStates
{
Good,
Bad,
Disabled
};
public static class PLCSafeStates
{
public static event EventHandler testStates1Changed;
private static PLCStates _testStates1;
public static PLCStates testStates1
{
get { return _testStates1; }
set
{
if (value != _testStates1)
{
_testStates1 = value;
if (testStates1Changed != null)
testStates1Changed(null, EventArgs.Empty);
}
}
}
}
And then in the pages hosted by the window, I have things like:
public FB1()
{
InitializeComponent();
SafteyFaults.PLCSafeStates.testStates1Changed += PLCSafeStates_testStates1Changed;
}
private void PLCSafeStates_testStates1Changed(object sender, EventArgs e)
{
var test2 = SafteyFaults.PLCSafeStates.testStates1;
if (test2 == SafteyFaults.PLCStates.Bad)
{
VisualStateManager.GoToState(btnFB, "PLCBad", true);
}
if (test2 == SafteyFaults.PLCStates.Good)
{
VisualStateManager.GoToState(btnFB, "PLCGood", false);
}
}
private void btnFB_Click(object sender, RoutedEventArgs e)
{
VisualStateManager.GoToState(btnOut1, "PLCBad",false);
if (SafteyFaults.PLCSafeStates.testStates1 == SafteyFaults.PLCStates.Good)
SafteyFaults.PLCSafeStates.testStates1=SafteyFaults.PLCStates.Bad;
else
SafteyFaults.PLCSafeStates.testStates1 = SafteyFaults.PLCStates.Good;
}
(right now, I don't have any business logic wired up yet- once I get this working, I'll link to actual data).
Anyhow, all of this works to create a single field I can subscribe to, modify, etc. But I need 20+ of these fields. I want to make 'testStates1' an array, but I've not been able to get it to work.
If I make the following edits to the code shown so far, it compiles and runs, but throws an error when I actually try to access the field (e.g. click on the button to change it):
//window
public static class PLCSafeStates
{
public static event EventHandler testStates1Changed;
private static PLCStates[] _testStates1;
public static PLCStates[] testStates1
{
get { return _testStates1; }
set
{
if (value != _testStates1)
{
_testStates1 = value;
if (testStates1Changed != null)
testStates1Changed(null, EventArgs.Empty);
}
}
}
}
//page
public FB1()
{
InitializeComponent();
SafteyFaults.PLCSafeStates.testStates1Changed += PLCSafeStates_testStates1Changed;
}
private void PLCSafeStates_testStates1Changed(object sender, EventArgs e)
{
var test2 = SafteyFaults.PLCSafeStates.testStates1[0];
if (test2 == SafteyFaults.PLCStates.Bad)
{
VisualStateManager.GoToState(btnFB, "PLCBad", true);
}
if (test2 == SafteyFaults.PLCStates.Good)
{
VisualStateManager.GoToState(btnFB, "PLCGood", false);
}
}
private void btnFB_Click(object sender, RoutedEventArgs e)
{
VisualStateManager.GoToState(btnOut1, "PLCBad",false);
if (SafteyFaults.PLCSafeStates.testStates1[0] == SafteyFaults.PLCStates.Good)
SafteyFaults.PLCSafeStates.testStates1[0]=SafteyFaults.PLCStates.Bad;
else
SafteyFaults.PLCSafeStates.testStates1[0] = SafteyFaults.PLCStates.Good;
}
Problem
Problem only comes when I try to insert. However I could browse through records. When I insert a new record, the UserControl does not consider the value I typed in, instead it stores as null. I basically think on New record, it does not sync.
The Form Layout
Purpose of UserControl
The DB stores Field value in the form of JKB-932340094VN00 where I use my UserControl for split Values by - and display it in 2 TextBox in it. So one TextBox will have the Value of JKB and other will have 932340094VN00
UserControl is as follows:
public partial class ucClientAccountIDParser : UserControl, INotifyPropertyChanged
{
public ucClientAccountIDParser()
{
InitializeComponent();
id = "JKB-821230063VN00";
txtClientAccountID.TextChanged += new EventHandler(clientaccountIDChanged);
txtCustodyID.TextChanged += new EventHandler(custodyIDChanged);
}
private string _clientaccountID = string.Empty;
public string ClientaccountID
{
get { return _clientaccountID; }
set
{
_clientaccountID = value;
txtClientAccountID.Text = this._clientaccountID;
}
}
private string _custodyID = string.Empty;
public string CustodyID
{
get { return _custodyID; }
set
{
_custodyID = value;
txtCustodyID.Text = this._custodyID;
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public string id = string.Empty;
[System.ComponentModel.Bindable(true)]
public string Text
{
get
{
return id;
}
set
{
id = value;
if (id != null)
{
string[] aVal = id.Split('-');
if (aVal.Length > 1)
{
this.CustodyID = aVal[0];
this.ClientaccountID = aVal[1];
}
else
{
this.ClientaccountID = id;
}
}
else
{
this.CustodyID = string.Empty;
this.ClientaccountID = string.Empty;
}
NotifyPropertyChanged(id);
}
}
public void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
private void clientaccountIDChanged(object sender, EventArgs e)
{
this.id = string.Format("{0}-{1}", txtCustodyID.Text, (sender as TextBox).Text);
NotifyPropertyChanged(this.id);
}
private void custodyIDChanged(object sender, EventArgs e)
{
this.id = string.Format("{0}-{1}", (sender as TextBox).Text, txtClientAccountID.Text);
NotifyPropertyChanged(this.id);
}
}
This is how I bind it:
try
{
this.Init(null);
this.Text = "General Account Add/Change";
objTable = new ClientAccountBusinessTable();
this.PrimaryDataAdapters = new ClientAccountBusinessTable[1] { objTable };
this.PrimaryDataGridView = null;
objTable.KeyDBField = "CLIENTID";
PrimaryBindingSource = new BindingSource[1] { bindingSource1 };
PrimaryDataSet.Tables.Add(objTable.GetBusinessTable());
SetKeyDBControl(new Control[1] { ucClientAccountIDParser1 }, new string[1] { "CLIENTID" });
ucClientAccountIDParser1.DataBindings.Clear();
ucClientAccountIDParser1.DataBindings.Add(new Binding("Text", this.bindingSource1, "CLIENTID"));
bindingSource1.DataMember = this.PrimaryDataSet.Tables[0].TableName;
bindingSource1.DataSource = this.PrimaryDataSet;
}
catch (Exception ex)
{
objTable = null;
throw ex;
}
I cant figure out why it takes null. Let me know if I carried out design of UserControl in proper way.
I hope anybody can help me out.