Category Archives: Substitution

[RESOLVED] best way to handle having user submit long text

I have a web application where users are permitted to submit their resumes. When the form is submitted, the data is inserted into a new record in an SQL table.

One of the fields in the form allows them to copy and paste their entire resume text into a TextBox control, which is inside the InsertItemTemplate of a FormView. This particular control is bound to a column in the SQL table that's of datatype nvarchar(MAX).

It works, but there are no line breaks and when viewed the resume is just one long continuous block of text.

How can I change this so that line breaks are preserved?

Do I need to use something like a "cute editor" control?

And finally, how do I protect against malicious code? The insert query is parameterized, and the FormView refers to an insert method in a TableAdapter in my dataset.

Thanks.


Line breaks in Textbox control is just line notepad - they represented by carriage returns, not the HTML <br> tags.

When displaying in html, just do a replace...  resumeText.Replace("\n","<br/>") 

Using the textbox is safer than "cute editor" as it prevents the ability for users to input html format which may contain malicious client side script and poorly formatted html. Just need to do proper replacing of single quotes which the equivalent "&039;". Single quotes in the query string are dangerous for sql injection. Also strip any html tags from the content.

Thanks for the explanation.

Just curious, though, how come the "\n" doesn't appear in the output?

Should I do the substitution in the code behind of the page that displays the resume?

And the other replacements you mention....where would that happen? In the INSERT query itself?

I tried this:


And got an error:

Server Error in '/' Application.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1061: 'object' does not contain a definition for 'Replace' and no extension method 'Replace' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Source Error:

Line 16:             <p><asp:Label ID="date_postedLabel" runat="server" Text='<%# Convert.ToDateTime(Eval("date_posted")).ToShortDateString() %>' /></p>
Line 17: <p><asp:Label ID="categoryLabel" runat="server" Text='<%# Eval("category") %>' /></p> Line 18: <p><asp:Label ID="resumeLabel" runat="server" Text='<%# (Eval("resume")).Replace("\n","<br />") %>' /></p> Line 19: <p><asp:Label ID="fileLabel" runat="server" Text='<%# Eval("file") %>' /></p> Line 20: </ItemTemplate>


Source File: e:\Ed data\clients\Maine Innkeepers\MIA website 2010\Maine Innkeeper Site 2010\member\resume-detail.aspx    Line: 18

 

What am I doing wrong here?

OK, I have this working now, for some reason I had to add .ToString() to resolve the error:

<asp:Label ID="resumeLabel" runat="server" Text='<%# Eval("resume").ToString().Replace("\n","<br />") %>'/>


Thanks for the help.

Still curious about the second part of my question, though, regarding where to check the string before the insert happens. 

If you're worried about malicious code, then use a Stored Procedure to store data back to the database. Stored Procedures will take the values as they are w/o processing anything as extra code.

Or you could go through and remove any database keywords of the Resume like DELETE or UPDATE and removing ;'s on the coding side of things before the database gets updated. 

 

Hi,

Alternative way, if the user resume included html format, you can also consider to use some editor control, like freetextbox or richtextbox. Use these control, you do not care about the format of user input.

Mister Ed

how do I protect against malicious code

Use parameterized value can prevent the sql injection attack to a great extent. You do not very worried about this.

And about script attacks. You can also use page validateRequest=true or server code Server.HtmlEncode to detete and encode user input before insert to database.

More information about Injection Attacks you can check these useful articles:

http://msdn.microsoft.com/en-us/library/ff647397.aspx

http://msdn.microsoft.com/en-us/library/ff649310.aspx

Hope this can help you.

[RESOLVED] Embedding Files in an assembly

I have an embedded file in an assembly.  It looks something like this:

<Assembly: WebResource("File.css", "text/css", PerformSubstitution:=True)>

And is called like this:

Page.ClientScript.GetWebResourceUrl(Me.GetType(), "File.css")

Everything works just fine, except for every once in a while, I get a slew of http file not found errors when the browser trys to access the resource WebResource.axd?d={0}.  (where {0} is some long encoded identifier).

Is there a way to give each resource a consistant identifier or name?

Hi,

Are you getting these errors in the browser or just in the log files? If you see them in your log files it is usually because someone is using a cached page and then the autogenerated id is out of date, and the resource can not be found.

/Johan

Log Files...That makes perfect sense after reading: http://www.eggheadcafe.com/tutorials/aspnet/2d46e075-3cdf-44d5-b2b6-f27c1f3beb34/using-the-webresourceaxd-handler-with-embedded-aspnet-resources.aspx.

So if I let a build sit for a few days, the frequency of these events should decrease?

Hi,

You will probably see them quite often since pages are cached at a lot of places, for example if your pages are indexed by any search engine like Google they will often try to access them by using a cached page first. I saw this error often in my logs when pages where accessed by IPs from search engines.

/Johan 

[RESOLVED] Partial caching of pages.

Hello All,

Is it possible to cache a page but not cache one of the page user controls? If so how do I accomplish this.

 

I'm using VS 2008 and .net 3.5

I believe this article should help.

[RESOLVED] Calculate sum of textbox values

Hi, I have about 12 sets of textboxes wherein lets say (for set 1), txt1 is the quantity, txt2 is the rate and txt3 is the supposed to be the total amount (txt1 * txt2). I need to calculate the total for all the 12 sets and hence writing individual javascript formulas is way too tedious and way too lengthy also.

I have been searching the net for a typical javascript formual which will calculate the total amount on "onblur" event of quantity textbox (txt1). I understand i have to pass the parameters to the function and also the function should return the total amount as a return value to the 3rd parameter passed as an argument to the function. Trying directly gives different errors on runtime. Gathered that i will have to use the ClientID, in which case i would have to hardcode formulas and parameters for all 12 sets.

Is there any way i can pass 3 parameters to a javascript function, 2 of which will be calculating fields (txt1 and txt2) while the 3rd will the resultant field. The formula should be such that the onblur event should be able to put the total amount in the 3rd field for each set.

Hope i have expressed the problem in a proper manner and would deeply appreciate a fully functional formula to the above.

 

Using VWD 2010 and SQL Server as the database.

Any help will be appreciated. Thanks

Tommy

Hi, yes it is possible to pass controls to javascript function. Following is the example. Please format it yourself as something is strange with my post:---------------- -------------<script language="javascript"> function calculate(ctrl1, ctrl2,ctrl3) { var c1 = document.getElementById(ctrl1); var c2 = document.getElementById(ctrl2); var c3 = document.getElementById(ctrl3); if (c1 != null && c2 != null) { c3.value = Number(c1.value) * Number(c2.value); } } </script> ----------------------------------------------------------------------------When you call this function, call it like ---------------------------------------------------------------------------------------<asp:TextBox ID="txt3" runat="server" onblur='javascript:calculate("txt1","txt2","txt3")'></asp:TextBox>

Thanks Adeel,

I tried the above snippet on IE 8. It did not generate any errors but also did not return any total. On putting alert boxes to debug, i saw that c1 and c2 are being returned as null and hence it is not able to calculate the total amount. If i put var c1 = document.getElementById(ctrl1).value i get an "object requried" message. please note txt2 already has a hardcoded text value. Yet it does not seem to work.

Also, is it ok, if i call the calculate function from the "onblur" of txt1, since txt3 might not and should not necessarily get the focus.

Thanks once again, I will try to tweak and see if i can manage.

 

Tom

Hi,

Yeah u are right it should be on blur of txt2, I must have done it by mistake. But I checked the following code and it is working on my side:

function calculate(ctrl1, ctrl2,ctrl3) {
           
            var c1 = document.getElementById(ctrl1);
            var c2 = document.getElementById(ctrl2);
            var c3 = document.getElementById(ctrl3);
           
            if (c1 != null && c2 != null & c3!=null) {
                c3.value = Number(c1.value) * Number(c2.value);
            }
        
        }

And call it like:

<asp:TextBox ID="txt2" runat="server" onblur='javascript:calculate("txt1","txt2","txt3")'></asp:TextBox>
Make sure that you specify the ids of textboxes correctly and using double quotes in single quotes like above.

Sometimes the ClientID of a control (what the javascript can "see") differs from the ID you give it in ASP. Normally because you are using master pages or databound controls like gridviews or repeaters.

Try this in your Page_Load event:

C#:

txt2.Attributes["onblur"] = "javascript:calculate('" + txt1.ClientID + "','" + txt2.ClientID + "','" + txt3.ClientID + "');";

VB

txt2.Attributes("onblur") = "javascript:calculate('" & txt1.ClientID & "','" & txt2.ClientID & "','" & txt3.ClientID & "');"

Thanks Guys, I was tweaking myself with the initial guidance from Adeel. It did not work with the initial code. However, i managed to get it working (atleast on IE8) with the following substitution:

 

<td class="AllTextBoxes" width="35px"> <asp:TextBox ID="txt1_Adult" runat="server" onkeypress="return isOnlyNumberKey(event)" onfocus="select();" onblur='calculate("ContentPlaceHolder1_txt1","ContentPlaceHolder1_txt2","ContentPlaceHolder1_txt3")' Width="35px" Style="text-align: center"></asp:TextBox> </td>

function calculate(ctrl1, ctrl2, ctrl3) { var c1 = document.getElementById(ctrl1).value; var c2 = document.getElementById(ctrl2).value; var c3 = document.getElementById(ctrl3).value; var totalAmount = (c1 * c2); document.getElementById(ctrl3).value = FormatValue(totalAmount); } function FormatValue(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }
The FormatValue funciton ofcourse, formats the string to 9,999,999.99 format. I will try to apply the above to all sets as mentioned before and hope it works. Nonetheless many thanks to you guys! Tom

I looked over the page to see if i could find out how to post a code block, but could not find any command toolbar. Used Opera and IE 8. Did I miss something somewhere? Tom