Add additional text on TextChange asp.net - 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

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.

ASP.NET membership provider, custom login control

I'm using the ASP.NET membership provider on my website. It works fine while using the Login Control in Visual Studio. However, I feel the Login Control has its limitation and I'm having a hard time making it fit to the design of my page. So instead of using that Login control, I'd like to be able to just create two TextBox's and a Button myself and use that to login instead. So my question is, can I create a custom login page with by creating my own textbox's and buttons? The code behind Login.aspx that I use with the login control right now looks like this:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)
{
Login1.Visible = true;
Session["user"] = User.Identity.Name;
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);
}
else
{
Response.Write("Invalid Login");
}
}
I tried changing Login1.UserName to TextBox1.Text and so on, but that didn't work. Any help is appreciated, thanks!
You should be removing Login1_Authenticate event and have a login button event to validate the credentials.
Or depending on how you submit back to server, such as ajax calls etc.
You can also use fiddler to see what's exactly being posted back to server.
PS. Why do not use ASP.net MVC?

calling alert from code-behind

i have a dropdownlist and a listbox both asp.net controls
i am trying to prevent the user add duplciate items to listbox control
i able to block it but i want to display DIV or Alert box saying,"duplciate names are not allowed"
protected void btn_AddRecipientAction_OnClick(object sender, EventArgs e)
{
if (Convert.ToInt32(this.ddlRecipient.SelectedValue) > 0)
{
if (ddlRecipient.Text.Length > 0)
{
//var items = new System.Collections.ArrayList(this.lstRecipient.Items);
for(var i = lstRecipient.Items.Count - 1; i >= 0; --i)
{
if (lstRecipient.Items[i].Text == ddlRecipient.SelectedItem.Text)
{
lstRecipient.Items.RemoveAt(i);
**//alert("duplicate entry not allowed")
//div display the message and disappears after few seconds?**
}
}
ListItem newList = new ListItem();
newList.Text = ddlRecipient.SelectedItem.Text;
newList.Value = ddlRecipient.SelectedValue;
this.lstRecipient.Items.Add(newList);
}
}
}
alert way:
You could use this line assuming you have a ScriptManager
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),"alert","alert('duplicate entry not allowed');",true);
This, however still does a postback since the script is run when the page is loaded again after the click. A better solution is to validate in client using javascript before submitting the page.
What you want is actually two separate things.
You should be validating on in the code behind, checking for duplicates on the post back. Then, use some javascript to do the same check on the client.
You MUST check for duplicates on the server since the user may not have javascript turned on.
Wow! Please don't inject js in the page to alert the user. You should instead have a notification control that receive a dataset of messages like an array then display the messages to the user. You want to separate your concerns.
You can achieve that in js. At the server you can set the array in json in a hidden field and then at the document ready event in js read that json data, parse it and loop on the array and display you messages. If you must you can use alert to display them but you should avoid it since it's so 1990's.
But I would go beyond that. I you do all the processing and validation in javascript before it gets to the server. So you don't rely on a post back to execute your validation. So as soon as the user adds the item it's told that it's a duplicate. Then, once the list is filled by the user he could save with a ajax call or post the page and at the server you parse the list, validate it and save it. If you have to compare the list to one already persisted at the server you can do that there. SOme thing goes wrong? you add the message to the notification control.
Please think about it. Try using a framework like MVC to separate you concerns. I makes the hole thing much faster to develop and so easier to maintain.
To call some JS from the code behind you can use Page.ClientScript property and call the RegisterStartupScript() method
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Can I hook up to any forms authentication sign out event?

I would like to do som extra processing whenever a user is signed out from forms authentication.
According to this MSDN article
there is a
FormsAuthentication_OnAuthenticate
event but I need something like a
"FormsAuthentication_OnSignOut" (Which doesn't exist)
Any ideas?
/J
Keep the user signed in until they explicitly sign out - and when they click the logout link use something like the following:
private void OnLogOut (Object sender, EventArgs e)
{
FormsAuthentication.SignOut ();
//extra processing here
}
As far as I have been able to find out there are no way to make this hook.
You have to add any extra code to the place where you do the FormsAuthentication.Signout().
(Of course you could apply some AOP techniques but this was not relevant in my case)

How can I do <form method="get"> in ASP.Net for a search form?

I have a search form in an app I'm currently developing, and I would like for it to be the equivalent of method="GET".
Thus, when clicking the search button, the user goes to search.aspx?q=the+query+he+entered
The reason I want this is simply bookmarkable URLs, plus it feels cleaner to do it this way.
I also don't want the viewstate hidden field value appended to the URL either.
The best I could come up with for this is:
Capture the server-side click event of the button and Response.Redirect.
Attach a Javascript onclick handler to the button that fires a window.location.replace.
Both feel quirky and sub-optimal...
Can you think of a better approach?
Use a plain old html form, not a server side form (runat=server), and you should indeed be able to make it work.
This could however be a problem if you have an out of the box visual studio master page which wraps the entire page in a server side form, because you can't nest forms.
Web forms don't have to suck, but the default implementations often do. You don't have to use web forms for everything. Sometimes plain old post/get and process request code will do just fine.
I worked on a web site that had to post to a 3rd party site to do the search on the client's web site. I ended up doing a simple Response.Redirect and passed in the search parameters through the query string like so:
protected void Button1_Click(object sender, EventArgs e)
{
string SearchQueryStringParameters = #"?SearchParameters=";
string SearchURL = "Search.aspx" + SearchQueryStringParameters;
Response.Redirect(SearchURL);
}
And on your Search.aspx page in your pageload...
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["SearchParameters"]))
{
// prefill your search textbox
this.txtSearch.Text = Request.QueryString["SearchParameters"];
// run your code that does a search and fill your repeater/datagrid/whatever here
}
else
{
// do nothing but show the search page
}
}
Hope this helps.
This function permits to submit a page using the GET method.
To submit a page using the get method you need to:
add this code Form.Method="get"; in the Page_Load method
Use this code < asp:Button runat="server" ID="btnGenerate" /> as a submit button
add rel="do-not-submit" attribute to all form elements that you don't want to include in your query string
change the codebehind logic of your page using Request.QueryString
disable the page viewstate with EnableViewState="false" (unless it's used for other purposes)
Code
$(document).ready(function(){ enableSubmitFormByGet(); });
function enableSubmitFormByGet(){
if($("form").attr("method") == "get"){
$("form").submit(function() {
$("[name^=" + "ctl00" + "]").each(function(i){
var myName = $(this).attr("name");
var newName = "p" + (i-1);
$(this).attr("name", newName);
});
var qs =$(this).find("input[rel!='do-not-submit'],textarea[rel!='do-not-submit'],select[rel!='do-not-submit'],hidden[rel!='do-not-submit']").not("#__VIEWSTATE,#__EVENTVALIDATION,#__EVENTTARGET,#__EVENTARGUMENT").serialize();
window.document.location.href = "?" + qs;
return false;
});
I would do (b) since (a) would require two round trips for a single query. Alternatively, you could disable viewstate on the page, remove any other hidden fields via javascript, and also use javascript to modify the form method from post to get. I've never done this for real, but my toy page using the included sample worked like a charm. It's arguably easier than encoding the search string and doing the get via javascript.
Actually, it sounds like you would be happier with ASP.NET MVC since this is easily doable there by simply setting the form method to GET in the view.
sample code using jquery
$(document).ready( function() {
$('input[type=hidden]').remove();
$('form').attr('method','get');
});
EDIT: It seems like you ought to be able to do the same thing server-side, too. Maybe in OnPreRenderComplete. Don't have access to Visual Studio right now to check.
I have always used Response.Redirect as it "works".
I don't think there is an optimal method.
Just use this in your .click event before the form submission:
$("#__VIEWSTATE").remove();
$("#__EVENTVALIDATION").remove();

Resources