How to restrict the user that is already connected - asp.net

I am working in Asp.net and I want to restrict the user while login, if the same user is already logged in or already connected.. I am creating a table in sql server USERS_CONNECTED and placed a single field USER_ID in it. When ever a user is logged in it's id is searched in USERS_CONNECTED table. If id is not found then the user is allowed to connect and the user id is added in the said table. But the problem is when the X button(present on right top corner of the browser) is clicked to exit then the user id should be deleted from the USERS_CONNECTED table. WHERE SHOULD I WRITE THIS CODE ?? I MEAN ON WHAT EVENT ..
can anyone help...
Dev..

You can handle end of a session. Add something like this to global.asax.cs file:
protected void Session_End(object sender, EventArgs e)
{
// Remove user from the USERS_CONNECTED table
}
Just one thing to remember: it will not be fired immediately when the user closed his browser. This event will be fired when the session expires.

To me it sounds like you are trying to implement a form of authentication. What you can do is use Forms authentication that uses a cookie that will keep track of the user's activity. Have a look at this tutorial to see how it is implemented: Forms Auth Tutorial

Related

How to do the proper login in a website

I am a new bee creating an asp.net web application for my application. I will have different users and i didn't use any special forms or methods to do the login. I have access db , in there i have some user role, company,username , and password.
In my login page through text box i will get company username and password inputting by the end user. then i will check for the company and username (which is primary key in the table.) if the password matches then will find the user role and redirect to the pages for each user.
that works fine now.
I have a log out button which is sitting in the sitemaster page and
<div id="logout" runat="server" visible="false" class="navbar-brand1">
<a id="lo" runat="server" href="/Default">Log Out </a>
</div>
then in the pages where i want to show the log out i will call the code
Master.FindControl("logout").Visible = true;
it was working fine in respect of login in and login out . but infact the log out button just redirects to the first page on site and if we do the back arrow in the browser i can go back to the prevs page i was on. Is there any way i can do it neatly so that after log out even though if i go back on the browser it will ask for log in .
Any help will be really appreciated. I made a mistake and created complete application now i am worried about this feature so technically i am not logging out :(
Whenever a user opens a page in the system use below code to check if the session is valid
if (!IsPostBack)
{
if (Convert.ToString(Session["UserName"]).Length <= 0)
{
Response.Redirect("Login.aspx");
}
}
When the user clicks on SignOut button, make redirection to a SignOut.aspx page. Use below code in the form load event of SignOut.aspx to clear the session.
protected void Page_Load(object sender, EventArgs e)
{
Session.Abandon();
Session.Contents.RemoveAll();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
Well, your question is how to do the
proper login
The proper way is not to reinvent the wheel, but use the framework that is built in in ASP.NET
https://msdn.microsoft.com/en-us/library/ms731049%28v=vs.110%29.aspx
It will give you a lot of extra features, like using OpenAuth etc.
Example
"https://msdn.microsoft.com/en-us/library/aa354509%28v=vs.110%29.aspx
As #Chathuranga Ranasinghe mentioned I used session varibale to store the username details and i will check if the session variable empty then go to my default page otherwise continue.
if (((string)Session["iden"]) )
{
Response.Redirect("/Default.aspx");
}
i used this on the pages comes after logged in and it works fine for me now.

How to make the registration details available to main page in Asp.Net?

I am building a web application which has a registration page ,login page and main page. User enters details in registration page for the first time(username,password,mail id,phone number) and on successive visits enters details in login page(Username and password only)
I need the following to be achieved
Make the mail id that the user gave on registration available to the main page
My code for this
//Code in registration page for fetching mail id
protected void Page_Load(object sender, EventArgs e)
{
Session["txt1"] = TextBoxname.Text;
}
//code for displaying the mail id fetched from registration page
protected void Page_Load(object sender, EventArgs e)
{
WelcomeUsername.Text = (string)Session["txt1"];
}
I am not able to display the mail id because the registration page is used only for a single time that is during registration but if a regular user logs in the user will fill details in login page.So how can I make the registration details available to main page in case of regular user(one who is not using registration page each and every time).Please help.I am new to .Net.Thanks in advance
Be aware that Session won't last forever.
Pseudocode would be something considering that you want to do the way you mentioned:
Store user data somewhere (database, file, etc.) and store ID in the Session
Get ID from the Session
Find the required ID in the database and retrieve the needed info (in your case e-mail)
its simple use, put the email textbox value below here
formsauthentication.setauthCookie(email.text,false)
and use asp:loginView for login thats it ,hope this helps you

Add additional text on TextChange asp.net

Reason i'd like to add additional text is because, for whatever reason when i try to login and it wants me to add "#domain.local".
Is it possible to add that automatically? I tried converting it to a template and used UserName_TextChanged but it didn't like what i was trying to do.
Any ideas?
Thanks.
Based on the information on the web.config you are using Forms Authentication with an LDAP provider. I am going to make the assumption that you are using the ASP.NET Login control on your page.
In order to handle the appending of #domain.local to a user name prior to login you should handle the LoggingIn Event from the control with something similar to the following:
void OnLoggingIn(object sender, System.Web.UI.WebControls.LoginCancelEventArgs e)
{
if (Login1.UserName.IndexOf("#domain.local", StringComparison.OrdinalIgnoreCase) == -1)
{
Login1.UserName += "#domain.local";
}
}
Of course you probably need a more precise process to determine the proper way to handle the user name.
You can find more information about the login control and its events here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.loggingin(v=vs.110).aspx

ASP.NET Web Form and F5 refresh issues

I have an ASP.NET Web Form (C#) that users fill out, it has a couple of drop down lists that cause post backs and some validation that causes post backs. I also use a couple of different update panels. One panel is visible for user input and the other panel appears after the user clicks submit and the data is added to the database. The confirmation panel (the last panel) also displays a confirmation number to the user.
After the last panel displays, I would like to prevent the page from reloading when the user presses F5 or refresh. The reason is, I don't want the user to accidentally click refresh or F5 and lose the confirmation number and message. When the user presses F5, the browser interprets it as wanting to load a new page and at that point the session is cleared (as indicated in code below).
My first thought was to reprint the message and confirmation number and make sure that the panel holding it stayed visible. I was going to do this in the else section of the code below - but since there are multiple postbacks and they all trigger the page load, that doesn't work, unless there is someway to determine if the postback is the result of a form element or the f5 key.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
Session.Clear();
GetList();
}
}
catch (Exception ex)
{
//Do something();
}
}
I've seen a few different posts that recommend using Javascript, but I am avoiding that if possible, in the remote chance that someone has javascript turned off.
Here is the flow of the program:
User opens form, fills in fields in the contactpanel and the clicks submit. The fields are validated using ASP.NET server validation controls and if everything is good, the data is sent to the database and a confirmation number is returned. Finally, the contactpanel is set to visibility=false and the confirmationpanel is set to visibility=true.
Hope this helps. Appreciate any suggestions.
Thanks,
Move your content that's on the final screen (the confirmation) to an entirely new page. Whatever data is saved to get to that confirmation should go in some type of data storage (like a database), and then whatever ID or variables the visitor needs to pull that information should go in a Session var. This way when the user refreshes the page, they will still see the content as you intend. It's pretty much how we had to do all forms back in the day anyway.
For instance:
~/form_page.aspx
- User lands
- Fills in information
- Post backs save data as the user progresses
- Save all data collected to a resource such as a database
- Save an ID to access that information to a Session variable
- Redirect user to...
~/form_thankyou.aspx
- On load, get the Session variable needed to pull the information
- Retrieve information from the resource
- Display results to user
(That's not actual code, I was just having trouble with the formatting.)
Using this technique will also make it easier on your SEO/Metrics team to track conversions (even though there are plenty of other ways).

Site Navigation and links hide/unhide based on permissions

I am developing a application using asp.net (C#) and this time the design concept is two frame based master page like left side will have navigation and right side frame will have content pages.
The navigation will have menu like the following.
System Parameters
........ Customer Setup
........ Currency Setup
........ User Management Setup
........ Group Definition
Transactions
..... Transaction 1
..... Transaction 2
..... Transaction 3
In Group Management I want to assign access permissions on forms and place users into the groups. Now my question is how to hide/unhide navigation links based on the group permission of logged in user.
I want to come up with the application design like the following
http://weblogs.asp.net/scottgu/archive/2006/01/17/435765.aspx
Please guide how to handle dynamic menu and build this type of application and restrict users not access the page on which he/she has no permission...most of the solutions over internet is based on web.config where roles are defined but I want to keep my roles in database along with the group permissions. so need solution based on database.
first, once a user logs in, you can store his/her authorisation level in a session variable. E.g. Session("CurrentUserLevel")="admin"
then,
to hide navigation items, you can write code to do:
if session("CurrentUserLevel") <> "admin" then
customerSetup.visible = false ' where customerSetup is your asp.net element
end if
to prevent pages from being accessed, place a code on top of each page:
if Session("CurrentUserLevel") <> "admin" Then Response.Redirect("hope.aspx")
note: this is a very simple and static/hard coded solution. Usually, you should use more advanced techniques to accomplish such tasks.
you gonna refer to the control via master page then change its visibility to current user
like this
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"]!=null)
{
liberarianDrop.SelectedValue = (Session["id"].ToString());
((LinkButton)this.Master.FindControl("LoginBtn")).Visible = false;}
}

Resources