How to indicate create user control if user already exists - asp.net

I am using Create User control with my own sql server database, I am not sure what event is there which can indicate the create user control to show its Duplicate UserName Error Message if there is an existing Username or email.
Please let me know.
thanks,

If you were using aspnet membership then CreateUser Control would have done the work itself. But from your question I guess you are not using so. In this case you will have to use logic to check for existing username. You can use Custom Validator and create a server side validation with it.
Example:
.aspx
<asp:TextBox ID="txtUserName" runat="server" MaxLength="150"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" OnServerValidate="CustomValidator1_ServerValidate"
ControlToValidate="txtUserName" Display="Dynamic"
ErrorMessage="UserName Already Exists"
ToolTip="Please select a different UserName" ValidationGroup="Register">
</asp:CustomValidator>
The code behind can have:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
SqlCommand objcmd = new SqlCommand("Select * from Login_Table where UserName='" + args.Value + "'",con);
SqlDataReader objReader;
con.Open();
objReader = objcmd.ExecuteReader();
if (objReader.HasRows)
{
args.IsValid = false;
}
else {
args.IsValid = true;
}
con.Close();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
// your registration code
}
Remember to keep the submit button under the same Validation Group as the Custom Validator i.e. "Register" in this case. You can have the control inside ajax update panel further. Hope this helps :)

Related

How to prevent a user from resubmitting a form?

I am developping a Single Page Application.
At the end of the application, the user gets to submit his contact information (name, phone number, etc). This sends an Email and modifies the page to a "Thanks for submitting [...]" page.
The problem is, the client can press the Back button and REsend the Email.
Is there a way to prevent this sort of.. spam?
Code
Sub BT_Send(sender As Object, e As EventArgs) Handles BT_Send.Click
Try
'Creating the Email Message
Dim mailMessage As New MailMessage()
mailMessage.To.Add("SomeOne#a.com")
mailMessage.From = New MailAddress("Robot#a.com", "Robot")
mailMessage.Subject = "Test"
mailMessage.IsBodyHtml = True
mailMessage.Body = LBL_Emailbody.Text & _
"<br><br><br><div style=""font-size: 0.7em;"">Robot speaking, I will not answer if you send me a message.</div>"
Dim smtpClient As New SmtpClient("Something.com")
smtpClient.Send(mailMessage)
PNL_Before.Visible = False
PNL_After.Visible = True
Catch ex As Exception
LBL_errorEmail.Visible = True
'Should never happen...
End Try
End sub
Here is a very simple example, where I use a static variable on page and avoid database.
the asp.net page is
<asp:Literal runat="server" ID="txtInfos"></asp:Literal><br />
<asp:TextBox runat="server" ID="txtEmail"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />/>
and the code behind.
static Dictionary<string, DateTime> cLastSubmits = new Dictionary<string, DateTime>();
private static readonly object syncLock = new object();
protected void Button1_Click(object sender, EventArgs e)
{
DateTime cWhenLast;
lock (syncLock)
{
var cNowIs = DateTime.UtcNow;
if (cLastSubmits.TryGetValue(txtEmail.Text, out cWhenLast))
{
if (cWhenLast > cNowIs )
{
txtInfos.Text = "Please contact us again after 10 seconds";
return;
}
else
{
// ok I let him submit the form, but note the last date time.
cLastSubmits.Remove(txtEmail.Text);
}
}
foreach(var DelMe in cLastSubmits.Where(x => cNowIs > x.Value).ToList())
cLastSubmits.Remove(DelMe.Key);
// if reach here, note the last datetime of submit
cLastSubmits.Add(txtEmail.Text, cNowIs.AddSeconds(10));
}
// and submit the form.
txtInfos.Text = "thank you for submit the form";
}
Some notes.
If you have many pools (web garden), then this may left user to
submit at the same time up to the pool you have.
Of course if a user submit fake data this can not protect you, and thats why we can use:
The honey pot trick.
captcha
Other control thats understands the bots
Code that understand the re-submit.

How to Apply Globalization On Web User Control in asp.net c#

i have applied globalization on default page but it is not applied on Web User Control.
I have created Header.ascx and put two linkButton one for English and second for spanish.
i am using code on header.ascx form code is below ... .
this code for english
protected void lbtnEng_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = "en";
Response.Cookies.Add(cookie);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
Server.Transfer(Request.Path);
}
this code for Spanish language
protected void lbtnSpan_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = "es-mx";
Response.Cookies.Add(cookie);
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-mx");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-mx");
Server.Transfer(Request.Path);
}
this code change language on default page label text but not on web user control label
declare control on default page
<asp:Label ID="lbl_test" runat="server" Text="<%$ Resources:Resource, Test %>"></asp:Label>
and on web control
<asp:Label ID="lbl_test" runat="server" Text="<%$ Resources:Resource, Test %>"></asp:Label>
you can set only one language at a time. In order to achieve your task .Use static strings or Take one resource file which consist of key value pairs. This is an example for submit key.
ResourceFileForStaticStrings.resx
Key Value
submitEnglish Submit
submitSpanish Presentar
Store it in a session or a cookie: Try the below one
System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(Session("es").ToString)
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(Session("es").ToString)

how to set column as readonly in gridview

I am using a gridview Edit to edit the values i have in my gridview, when i press edit, all columns can be edited, i would like that one of the columns is not allowed to be edited.
Is there any way i can do this?
This is my aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True"
onrowdeleting="GridView1_RowDeleting" AutoGenerateEditButton="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating" >
</asp:GridView>
This is my aspx.cs code:
public void loadCustomer()
{
SqlConnection objConnection = new SqlConnection("Data Source=localhost;Initial Catalog=SampleApplication;Integrated Security=True");
objConnection.Open();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandText = "Select * from Customer";
objCommand.Connection = objConnection;
objCommand.ExecuteNonQuery();
DataSet objds = new DataSet();
SqlDataAdapter objadap = new SqlDataAdapter(objCommand);
objadap.Fill(objds);
GridView1.DataSource = objds.Tables[0];
GridView1.DataBind();
objConnection.Close();
}
RowDataBound event of gridView1
((BoundField)gridView1.Columns[columnIndex]).ReadOnly = true;
I know this is really old but I need to put the answer here for others who shared my issue. Regardless, I've been struggling with this non-stop for a couple of days now. Everyone seems to be posting code for VB, when your problem is clearly posted in C#.
What you're looking for is:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columntobedisabled].Enabled = false;
}
where 'columntobedisabled' is index number of the column to be disabled...eg. 1
In case of C# Website or WebForm enter the following code in Page_Load() in code behind file
protected void Page_Load(object sender, EventArgs e)
{
// Your code
((BoundField)GridView1.Columns[columnIndex]).ReadOnly = true;
}
Doing this will also help in overcoming the error
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index'
You need to give rights "ReadOnly= true" to that column which you not like to be edit.
e.g .
GridView1.columns[1].ReadOnly= true;
You can use this line in RowDataBound event of GridView.

Insert data into Access database upon checkbox-click event of ASP.net

I'm trying to make asp.net page
Criteria
I have product list. (using listview)
ProductID Proudct name Price ADD TO CART(checkbox)
Now I am using access 2007 for database. C# for code behind file. I want add product in to database which is on the event of checkbox. So if user check 10 item check box Out of 20 . I want write insert query on event of checkbox
Is it possible to do it? If it possible please provide me knowledge/ code how can I do it?
Please keep in mid that I am new and learning stage so make it easy or put gudieline in comments.
It sounds like you want to use the OnCheckedChanged event.
<asp:CheckBox ID="CheckBox1" runat="server" Text="Hello World!" OnCheckedChanged="CheckBox1_CheckedChanged" />
And in your code behind:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
//CREATE CONNETION HERE
OleDbConnection conn = new OleDbConnection ("<YOUR CONNECTION STRING HERE>");
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
//CREATE YOUR OWN INSERT/UPDATE COMMAND HERE
command.CommandText= "<YOUR COMMAND TEXT HERE>";
command.Parameters.Add ("#Argument1", OleDbType.String).Value = CheckBox1.Text;
command.ExecuteNonQuery();
conn.Close();
}

cannot modify asp login in page_load or page_init

So I have an asp:Login field on my login page.
However, I want to use a path for the create account url and the forgot password url. So I have to do it in Page_Load or maybe Page_Init. Regardless, neither option works, it simply refuses to modify the login form.
protected void Page_Load(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.PasswordRecoveryUrl = forgotpath;
lgnMain.InstructionText = "test";
lgnMain.Focus();
}
protected void Page_Init(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.UserName = "test";
lgnMain.InstructionText = "test";
lgnMain.PasswordRecoveryUrl = forgotpath;
}
The CreateUserUrl and the PasswordRecoveryUrl are ignored if you haven't set the CreateUserText and PasswordRecoveryText properties respectively. Since the Text properties probably don't need to be dynamic, just set them in the ASPX (although you could still set them in the code behind if required), and then the dynamic setting of the URL properties (in the Page_Load event) should work without problem.
Documentation here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login_members(v=vs.85).aspx
From the Documentation above:
If the CreateUserText property is
empty, the link to the registration
page is unavailable to the user.
If the PasswordRecoveryText property
is empty, the link to the password
recovery page is not available to the
user.
have you tried setting it in the markup?
<asp:Login id="lgnMain" runat="server"
CreateUserText="Register"
CreateUserUrl="~/user/RequestAccount.aspx"
PasswordRecoveryText = "Forgot Password"
PasswordRecoveryUrl = "~/user/ForgotPassword.aspx" >
</asp:Login>

Resources