Text with RegEx Validator not working - c#

I have an issue with the following text display:
<asp:RegularExpressionValidator ID="Password_RegularExpValidate" runat="server"
Text="TEST!"
Display="Dynamic"
BorderStyle="None"
ControlToValidate="txtNewPass"
ValidationExpression="(?=^.{8,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*"
meta:resourcekey="Password_RegularExpValidateResource1" /></td>
The pattern by itself is:
(?=^.{8,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*
The text initially had some stuff in it as the ValidationExpression was different. I've changed the regex expression and that works, but when I write something in Text= it doesn't update on the page. I've restarted IIS, cleard the IE chache... everything I could think of. The old text keeps appearings (ie. "TEST!" doesn't show up when the validation fails as it should).
Any help would be appreciated.
Edit:
The code for txtnewpass:
<asp:TextBox ID="txtNewPass" runat="server"
TextMode="Password"
MaxLength="256"
meta:resourcekey="txtNewPassResource1"></asp:TextBox>
Also, it's worth noting that I can remove an entire table from a page that it disappears when I reload the page. But when I change text values from controls or anything that runat="server" and the page doesn't seem to update with the text....
And the code behind doesn't edit the field that displays, the validator validates the text in the textbox and uses that value later.
Edit 2: Same thing happening with -
<asp:Label ID="Label1" runat="server"
Text="Change Password!!!!!"
meta:resourcekey="Label1Resource1"></asp:Label></td>
I've added the exclamation marks (!!!!!) and that's not showing up when I refresh the page either.....
Edit 3: As I've noted in one of the comments, if I delete a table from the page and reload the page, that table disappears, so I know the page is reloading properly. The runat="Server" property, does that work a certain way where it caches text or something? I'm out of ideas....

Like Kirill said, use ErrorMessage instead of Text.
But the main problem is, I think, your localization, which is handled through the meta:resourcekey tag and resources.
Here is a good explanation:
ASP.NET meta:resourcekey
If you set automatically or manually the resource localization file and change something afterwards, for example a Label Text property, then you need to do it in the resource file too. Because there should be your initial value, which is loaded at runtime.

There are a lot of possibilities for the source of the problem, and there's not really enough info to tell which one it is. It sounds to me like one of these:
1) An external issue with your application or page (perhaps your ViewState isn't being set up properly, or the validation is getting called before PostBack).
2) You should be using RegularExpressionValidator.ErrorMessage instead of Text, as Kirill suggested. You said that you had changed that, but I wonder if you've reloaded the page (you could try rebuilding the app or something if it's getting cached somehow).
3) Your regex might not be doing what you think it is. The pattern is extremely long, and it seems strangely written. Adding some whitespace, we find that it looks like this:
(?=^.{8,255}$)
(
(?=.*\d)(?=.*[A-Z])(?=.*[a-z])
|
(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])
|
(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])
|
(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9])
)^.*
Which simplifies down to something like:
^(
(?=.*[A-Z])(?=.*[\W_])(?=.*[a-z\d])
|
(?=.*[a-z])(?=.*\d)(?=.*([A-Z\W_]))
).{8,255}$
Is this what you intended? I see where you're going with the password rules, but it may be easier to just simplify them and require one capital, one lowercase, one number, and one special character. You could also try to get validation working with a simpler regex pattern, and then add complexity once everything else is working.

Try to use RegularExpressionValidator.ErrorMessage instead of Text.
Try restarting VS. Sometimes incredible bugs disappear after that.
Try removing and regenerating your ..aspx.designer.cs file (to
regenerate right click the aspx/ascx file and choose "convert to web
application").
Agree with others, you should indeed check your resource file.

Related

ASP.net Web Forms - TextBox displaying wrong encoded text

I am stuck on this problem for a while now.
I did some searches on this and other sites, where the problems got solved, but sadly none worked for me.
Problem:
I develope an asp.net web forms application, for a list of reservations.
The name and prename data values can have german symbols in it (ä, ö, ü, ß).
Basically everything worked fine until I added an edit page for the reservations.
When I set the text of a textbox based on the data values, they text shows ö for ö, ä for ä, ü for ü and ß for ß.
The point is that this only happens in the asp:Textbox.Text, if I use it in a asp:Label.Text it shows the correct name.
So now the question is: Anyone else had this problem and if yes how did you fix it? If not, do you have any ideas how to fix it?
Code + Result Picture
P.S.: Yes everything is utf-8, yes I tried HttpUtility.Decode and such, nothing worked as said at start. In the database it is shown correct too. I can type in an ö without problem, just setting text doesn't work.
EDIT:
After Sonal Borkar's idea, I used a textarea but it is impossible to check a textarea with a RequiredFieldValidator. So now I was messing around in the .net-API and noticed some things:
Only listitem.cs and textbox.cs have this PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty),
set in their text-attribute, things like label.cs have PersistenceMode(PersistenceMode.InnerDefaultProperty).
Also listitem.cs and textbox.cs have an override in their ControlBuilder
public override bool HtmlDecodeLiterals() {
// ListItem text gets rendered as an encoded attribute value.
// At parse time text specified as an attribute gets decoded, and so text specified as a
// literal needs to go through the same process.
return true;
}
Other webcontrols like the label, don't override this method and their method returns false.
BUT still it doens't make any sense, because I have ListItem which has a german symbol in it and it gets rendered perfectly fine. So I am really stuck and confused why no one ever had to mess with this before.
Looking for a solution by myself, but still could use some help.
Edited:
Try below, Good Luck!
1) Use HttpUtility.HtmlDecode
<asp:TextBox ID="EditItem" runat="server" Text="<%#
HttpUtility.HtmlDecode(Item.Name) %>"></asp:TextBox>
2) Set Meta Tag in HTML
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
3) Set Globalization in Web.config
<globalization requestEncoding="utf-8" responseEncoding="utf-8"
fileEncoding="utf-8" />
4) Set the font-family in style of Textbox
<asp:TextBox ID="EditItem" runat="server" Text="<%#
HttpUtility.HtmlDecode(Item.Name) %>" style="font-family: Courier
New;"></asp:TextBox>
5) Replace Textbox with TextArea or RichTextBox
Solution:
After trying around for another few hours, thats the way I made it actually work, if anyone will ever find themselves in the same situation.
In your FormView add an empty TextBox as following:
<asp:TextBox ID="EditName" runat="server" CssClass="form-control" Text=""></asp:TextBox>
In your CodeBehind class, when the page is completely loaded, get your data from the database again, and call a method like this:
protected void GetNameAndPreName()
{
int reservationID = Convert.ToInt32(Request.QueryString["reservationID"].ToString());
ReservationContext _db = new ReservationContext();
Reservation r = _db.Reservations.SingleOrDefault(reservation => reservation.ReservationID == reservationID);
(reservationDetail.FindControl("EditName") as TextBox).Text = r.Name;
(reservationDetail.FindControl("EditPreName") as TextBox).Text = r.PreName;
}
In my case it's name and prename, change to whatever you need. This will the text will be shown correctly.
HINT: This does NOT work for multiline textboxes, as they get encoded everytime as seen in TextBox Source

How to get html control by ID that has hyphens?

I have a front end written in html that I am converting to asp, and many of the controls have names with "-" in them. This is causing crazy headaches, as there is no time to rename everything, and the ctrl-f and replace somehow breaks my css. Is there any way to access these controls in the code behind while they have the dashes? I have tried the code below.
//Can find when there is no dash in it, but that breaks the css after find/replace of full solution
HtmlGenericControl body = (HtmlGenericControl)this.Page.FindControl("page-list");
body.Attributes.Add("class", GlobalVariables.webAppSkin);
//I have also tried this, but logout stays null
WebControl logout = (WebControl)Page.FindControl("logout-link");
This is the html control:
<body id="page-list">
Sorry, that's not gonna happen.
You cannot have an element with an id containing "-", and still be a runat="server" ASP.NET control.
Microsoft's docs about the control's IDs states:
http://msdn.microsoft.com/en-us/library/system.web.ui.control.id.aspx
Only combinations of alphanumeric characters and the underscore character ( _ ) are valid values for this property. Including spaces or other invalid characters will cause an ASP.NET page parser error.
If you tried adding runat="server" to the body tag you showed: <body id="page-list">, it would give you the following line in aspx.designer.cs:
protected global::System.Web.UI.HtmlControls.HtmlGenericControl page-list;
Which is obviously throwing an exception on C# syntax.
<body id="page-list"> is not a HTML Control (i.e. an instance of (a subclass of) System.Web.UI.Control because it doesn't have the runat="server" attribute. If you were to add runat="server" then you would get a JIT compile-time error message informing you that "page-list" is not a valid identifier.
ASP.NET Web Forms 4.0 added the ClientIDMode attribute, however it doesn't allow you to set a completely custom ID attribute value. There's no easy solution for this without using <asp:Literal> or implementing your own control (or my preferred option: switching to ASP.NET MVC).
You can access controls in code behind with their ID if you write runat="server". Here is the example for your case
<body runat="server" id="testID">
In code behind you can access it like this:
body.Attributes.Add("class", value);

Problems reading form variables in asp.net C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Background: I've been asked to work on a legacy asp.net application for which there is no documentation and the original programmers are not available for consultation. I'm primarily a Perl programmer, primarily on *nix systems, so while I've no major problems with the actual logic of the system, I'm getting tied in knots by some of the "bare bones" stuff underneath.
Outline: I'm trying to extend an existing aspx form to increase its functionality, the form is part of a system for purchasing telephone numbers. At the moment, the form when first called shows a list of locations and telephone area codes in an HTML drop-down list, and expects the user to select one. When a value is selected (or selected and the select button clicked, if JS is disabled) and the form submitted, the page in postback mode then provides an appropriate redirect to a purchase page, with various values set in the query string. I want to extend the functionality by adding a second row of controls, on the same form, comprising a text box for users to enter an area code, and a "Search" button. The idea is that when a user does this, the system will then do a DB search for that area code, and if a match is found, generate the appropriate redirect to the page selling that area. All the code is (and will be) in C#.
The problem: Having found a lot of useful info here on Stack Overflow on extracting form variables from asp.net forms, I tried to retrieve my new variables using Request.form["variable_name"]. But it soon became clear the values weren't coming through.
Here's the aspx page code for the new bit of the form:
<tr>
<td align='left'><b>STD code:</b></td>
<td align='left'>
<asp:TextBox id="STD_Code_Search"
AutoPostBack="True"
Columns="7"
Text=""
TextMode="SingleLine"
Wrap="False"
runat="server"/>
</td>
<td><asp:Button ID="Button2" runat="server" Text="Search" /></td>
</tr>
I expected to be able to pull those variables back via
Button2_Clicked = Request.Form["Button2"]
STD_Code_Search = Request.Form["STD_Code_Search"]
However nothing ever came through. Based on more searches, I found this code to display all the variables coming into the form:
foreach(string key in Request.Form.Keys)
{
LOG.WriteLine(key + ": " + Request.Form[key] + "<br/>");
}
The LOG object is a StreamWriter going to a text file, which seems to work fine.
However the data in the file looks like this:
ctl00$ctl00$ctl00$ContentPlaceHolder1$Main$Range_Data$STD_Code_Search: 01952<br/>
ctl00$ctl00$ctl00$ContentPlaceHolder1$Main$Range_Data$Button2: Search<br/>
Fair enough, I then tried to use the following to retreive the data in C#
STD_Search = Request.Form["ctl00$ctl00$ctl00$ContentPlaceHolder1$Main$Range_Data$STD_Code_Search"];
That does actually work and if I send STD_Search to the StreamWriter LOG I can see the entered value in my text file.
However if I then try and read a second value (in this case I'm trying to catch the value of Button2, so I can trigger specific behaviour if that button, rather than the original one, is clicked), using this code:
STD_Search = Request.Form["ctl00$ctl00$ctl00$ContentPlaceHolder1$Main$Range_Data$STD_Code_Search"];
Button2_Clicked = Request.Form["ctl00$ctl00$ctl00$ContentPlaceHolder1$Main$Range_Data$Button2"];
Then while the asp.net processes all appear to complete correctly (no errors or page crashes), the writing of the text file stops dead and no data at all is written.
Questions:
I'm sure I shouldn't have to include all the placeholder stuff
(reading on here I gather that's part of the underlying framework
and asp should in fact just present me with the named variables, the
same as a Perl or PHP system would do with a plain HTML form), any
pointers as to why that might be happening and if there's anything
else I should be doing to process / extract the data?
Why does it all drop dead when I try and read in a second variable,
despite working (for some large values of working) when I only read
in one?
Are there any recommended books on asp.net and C#? I have
Sitepoint's "Build your own asp.net 4 website using C# & VB", which
has helped a bit but isn't so useful for trying to take someone
else's code apart and re-build it.
Prior research: I've done extensive searching on this, however most of the answers I've seen so far have been related to people using asp.net to process data submitted from external sites, etc, or by scripts using post directly. All the sites I've looked at for tutorials on asp.net appear to say I should just use Request.Form["variable_name"], so there appears to be something else going on here.
You should be using code-behind to do all this stuff. It will make it easier.
string searchText = STD_Code_Search.Text;
And to to know if a button was clicked, you would do
<asp:Button ID="Button2" runat="server" Text="Search" OnClick="Button2_Click" />
And have it processed
protected void Button2_Click(object sender, EventArgs e)
{
//button2 was clicked
}
Asp.Net is an event-driven framework, not like PHP or JSP. Pick a good book on Asp.Net and read. Most of the things you were trying to do have been handled for you by Asp.Net.
The Request.Form collection is only used when you want to access "raw" POST body contents directly. ASP.NET WebForms operates an abstraction layer which means you shouldn't normally need to use this collection.
Instead access submitted values by their parent controls. In this case the control is known as "STD_Code_Search" (an egregious violation of .NET's naming and style conventions, but I digress). Assuming you're using Visual Studio's tools, there will be an auto-generated file with the same name as your *.aspx file with the suffix "designer.cs" that will contain a class field called "protected TextBox STD_Code_Search;". All you need to do is access this field. Note that this field will only be populated after the Init page event.
string search = STD_Code_Search.Text;
Did you try how its supposed to work?
You should have a protected variable for each form control in your .cs file. Newer versions of visual studio do this for you (when you add server side markup tags), but basically if you've no intellisense in the .cs file for the variable .g.
STD_Code_Search
If it's not declared, just do this at top of page:
protected TextBox STD_Code_Search;
now when you post back STD_Code_Search.Text should have a value
That as I've said is how it should work.
Unless there's some compelling reason to use Request.Form you shouldn't go there, but its worth knowing its whatever is wrriten in the "name" attribute on the client-side (hence that horrendous placeholder stuff). It can be overwritten to something more pretty (options based on your asp.net version).

Restrict the text length assigned for Link Button from DB

I have some text being fetched from the DB, which I am binding to the DataList ItemTemplate in the following form:
<asp:LinkButton runat="server" Text='<%#Eval("url")%>' />
The text that is fetched from the DB might be long and I want to restrict it to (let's say 50 chars at max. with a ... afterwards) in the above eval assignment.
How can this be done here?
Secondly, how do I specify the link here in LinkButton so that on clicking on it, it goes to the specified, the link should open in a new window as in taget=_blank
You can use a tag directly
<a href='<%#Eval("url")%>' taget=_blank> <%# BindText(Eval("url"))%></a>
Codebehind:
public string BindText(obj url)
{
if(url!=null) {return (url.ToString().length > 50) ? url.ToString().Substring(0,50) + '...': url.ToString() ;}
return "";
}
One easy way to handle that would be to create a "Truncate" extension of type String which simply strips X characters from the end of it.
Regarding "target=_blank" - you should be able to accomplish this with the Attributes property of the LinkButton.
Depending on the target browser, using CSS text-overflow is an elegant way to do this at the client instead of the server (maximizes space; only that text which must be truncated will be truncated, and it also takes into account simple punctuation rules).
https://developer.mozilla.org/en/CSS/text-overflow
This blog post shows a decent solution in that it seeks whitespace in which to inject the ellipses (rather than blind truncation).
For setting the target of a LinkButton...
<asp:LinkButton runat="server" target="_blank">
ASP.Net will (usually) ignore attributes that it doesn't recognize and just render them to the client verbatim. However, this won't actually work because a LinkButton is meant to initiate a postback. You can use an anchor tag instead.

HTML string does not get verified

These spaces are not added by me on HTML SIDE and i cannot edit HTML
I want to know what should my comparison string?
I am using watin to automate website testing process but I am unable to encounter only one button.Every other works
watin searches content by name /values /id and many more and works fine but when i see the value of the submit button that i need to be clicked it has some breaks &nsbp so i think they are playing some role
Here is the html:
<span class='button'><input type="submit" value=" Login " /></span>
<span class='button'><input type="button" value=" Back " onclick="history.back(-1)" /></span>
and here is the code to search
browser.Button(WatiN.Core.Find.ByValue(" Login ")).Click();
what can be done??
-- Suggestion -- (i.e. too big for a comment)
You shouldn't use to add spaces to the submit button. Rather, you should use CSS to style the button to your liking. So you would have something like:
input[type=button] {
padding:10px;
min-width: 150px;
}
By the same token, this could eliminate any of the issues you're having with selecting the button. It could be an issue of encodings breaking with watin and as a result, doing this with CSS will make debugging the issue much cleaner and much easier.
Edit:
Have you tried searching by ID as opposed to by value? ID's are supposed to be unique on a page, so if it doesn't find it by those means, then that's one issue that can be rules out. It could also be the fact that you're searching for a button. A <button> is not the same as a <input type="button">.
Edit 2: Even though the issue was due to encodings breaking, I still recommend you reset that button to reset the text (removing all the non breaking spaces) and attach an id/name to it. The reason being for internationalization purposes - and if for some reason you modify the size of the button in the designer, or i18n the app and the text is different, your test will break.
You shouldn't use entities with WatiN.
This code will work, but you have to use real non-breaking space character:
browser.Button(
WatiN.Core.Find.ByValue(
"   Login   ")).Click();
This is probably inconvenient, but you could use (after adding reference to System.Web) HttpUtility class:
browser.Button(
WatiN.Core.Find.ByValue(
System.Web.HttpUtility.HtmlDecode(
" Login "))).Click();
But, if I were you, I would just go with Regex:
browser.Button(
WatiN.Core.Find.ByValue(
new Regex(#"^\s*Login\s*$"))).Click();
or even new Regex("Login").
Interesting thing: If you ever will have to Find.ByText you don't have to bother so much, and you can use regular space (ie. not exactly non-breaking space). That's because native IE IHTMLElement::getAttribute (http://msdn.microsoft.com/en-us/library/aa752280(VS.85).aspx) converts from innertext attribute to regular spaces, but from value, id etc. it doesn't ( are converted to real non-breaking spaces - 0xA0)
Wow, you really like spaces! I would remove those and use padding/margins like html was designed to be used. Then you wont need all those spaces and you can assign a proper value to your button which watiN will recognize.
I think it is because the in the HTML source is actually an escaped version of the special character that represents a none breaking space. So in you C# source, you'll probably need that character instead of the html entity code. I think you can find the code of that character by using this button to submit a GET form. It will show the escaped character code in the url.
Of course it is better not to put the spaces in there at all. You should give the button a padding using CSS instead.

Categories