How to operate with html radioButtons. Validation , checking if checked, collecting values? - c#

I need help. I'm trying to make a .Net, c# application for online creating surveys. I have a few types of questions, and than I dynamicly put labels, combos, textboxes ... on the form. Up to this point, I somehow managed to get. Than, on click on add button, I write down the responses in html format using stringBuffer and append function. Example.
public string RetOptionalQuestion(string seq_numm, string question, string answersOpt)
{
StringBuilder _output = new StringBuilder();
_output.Append(# " <tble><t"r"><th>" + seq_numm + "." + question + "</th></tr>");
_output.Append(#"<tr><td><table>");
string[] words = answersOpt.Split(';');
int m = 0;
foreach (string word in words)
{
if (word != "")
{
_output.Append(#" <tr><td> <label> " + word + "</label> </td> <td>
<input id='optional" + question + Convert.ToString(m) +
"'type='radio' name='rbOpt" + question + "' </td> ");
m++;
}
}
_output.Append("</table></td></tr></table>");
return _output.ToString();
}
Now, I hawe to validate this questions(at least one radio checked...). They have the same name,this mean the same group, so only on e can be selected.
Than I have also to save the values(responses) of this questions to the database.
Problem is that I don't know how to operate with this html objects. Also how to set tehm the ID-s. I'm trying with javaScript , but with no success. Do you have any advice, hint, example, solution ... where to start...
I would be very pleased
Thanks, Martin

Any input controls posted to the form can be found in the Request.Form dictionary, the key is the 'Name' attribute of the input tag. (I think)
http://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx

Related

if one html tag matches then another tag should be crawled using htmlagilitypack

<a class="product-name" href="http:xyz" title="Polac pineapple slices 3kg">Polac pineapple slices 3kg</a>
<div class="price-box">
<span class="regular-price" id="product-price-5489">
<span class="price">Rs 665</span> </span>
I want to get the price from the Span tag, but it should provide price of particular item when matched. like if a tag have inner text as Polac pineapple then it should return Rs 665
Following is code i'm using
`
var aTags = document.DocumentNode.SelectNodes("//a");
var nextTags = document.DocumentNode.SelectNodes("//span");
if (aTags != null)
{
foreach (var aTag in aTags)
{
s += counter + ". " + aTag.InnerText + "<br>";
//s += aTag.InnerText;
if (aTag.InnerText == "Polac pineapple")
{
brandcheck = true;
find += aTag.InnerText + " ";
foreach (var nextTag in nextTags)
{
//s += counter + ". " + nextTag.InnerText + "<br>";
s += nextTag.InnerText;
if (nextTag.InnerText.Contains("Rs"))
{
brandcheck = true;
find = nextTag.InnerText + " ";
}
}`
Can you be more precise?
You can use "id".
<span id="thisspan">A uniquely identifiable element.</span>
The id attribute provides a unique identifier for an element within the document. It may be used by an a element to create a hyperlink to this particular element.
The most important aspect of the id attribute is that it must be absolutely unique. Unlike the class attribute, which may apply the same value to many elements in a page, an id that’s applied to an element must not match an id used anywhere else on the same page.
The id attribute value must begin with a letter in the roman alphabet (a–z or A–Z); this can be followed by any combination of letters (a–z or A–Z), digits (0–9), hyphens (-), underscores (_), colons (:), and periods (.). The id value is case sensitive, thus This is me and This is me would be considered to be separate and uniquely identifiable elements on the same web page.

save listView content to a file

I'm trying to save the contents of my listView.
But I'm having some issues with it. In my text file it will look like this:
ListViewItem: {1234};ListViewSubItem: {daily};ListViewSubItem: {Backup};ListViewSubItem: {Every 2 days at: 23:0};ListViewSubItem: {};ListViewSubItem: {}
But I don't like that it adds "ListViewItem:" and "ListViewSubItem:" etc with my data.. I just want those strings inside {}.
And here is my code:
FileStream file = new FileStream(dataFolder + "\\BukkitGUI\\schedule.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(listItem + ";" + listItem.SubItems[1] + ";" + listItem.SubItems[2] + ";" + listItem.SubItems[3] + ";" + listItem.SubItems[4] + ";" + listItem.SubItems[5]);
}
sw.Close();
file.Close();
Any help on this?
EDIT: Image of my listView:
Your code does this:
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(listItem + ";" + listItem.SubItems[1] + ";" + listItem.SubItems[2] + ";" + listItem.SubItems[3] + ";" + listItem.SubItems[4] + ";" + listItem.SubItems[5]);
}
This is doing the following:
foreach (ListViewItem listItem in listView1.Items)
{
string listItemString = listItem.ToString();
// etc.
}
What do you think the value of listItem.ToString() will be?
The default implementation of object.ToString() simply outputs the name of the type. The implementation for ListViewItem and ListViewSubItem apparently output the name of the type, plus the content of the item or subitem.
If you want something different output, then you need to do it yourself. Output listItem.Text and listItem.SubItems[n].Text instead.
Q: If your input data is in JSON format, perhaps your best bet is to get a JSON parser?
For example:
Parsing REST Services JSON Responses (C#): illustrates System.Runtime.Serialization.Json
Otherwise, if it's just a "funny format", look at the .Net TextFieldParser:
Parsing Text Files with the TextFieldParser Object
It's too long to post it as comment so I'll write an answer. I hope at least it will give you a good direction on one way to deal with it. In general you need some way to manipulate string. Many options comes to mind, but in your case I think that using regex or regular expressions is the best option since they are powerful, you have a clear criteria about what should go inside the .txt file and what not, and you work with relatively small amount of data so even though the regular expressions are considered slower than other options, in your case I think this won't be a problem.
Here is what I've tried - just created a static method (some sort of helper method) that will clean the string for you so that you get only the info you need. The method itself is :
public static string ParseListView(string ListViewText)
{
var regex = new System.Text.RegularExpressions.Regex("{.*?}");
var match = regex.Match(ListViewText);
return match.ToString().TrimStart('{').TrimEnd('}');
}
Pretty simple method. There's a lot of things that you can adjust if needed to work better for your case. For example I'm using regex.Match() which returns only the first match, but maybe you'll find regex.Matches() more suitable for you. There are also a lot of other options when you work with regular expressions in C# so be sure to check them out.
Then in you foreach loop you just:
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(ParseListView(listItem) + ";" + ParseListView(listItem.SubItems[1]) + ";" + ParseListView(listItem.SubItems[2]) + ";" + ParseListView(listItem.SubItems[3]) + ";" + ParseListView(listItem.SubItems[4]) + ";" + ParseListView(listItem.SubItems[5]));
}
Of course this looks pretty ugly so the logic inside the foreach loop most probably can be improved but I think this will get you going.

Crystal report textobject and fields

i am running the following code
foreach (ReportObject obj in oSectionObjects)
{
if (obj.Kind == CrystalDecisions.Shared.ReportObjectKind.TextObject)
{
// do stuff
}
}
but i have a problem. i do have multiple text that do contain text AND fields in them.
But crystal return me the field being TextObject which is technically true.
How do i know i ONLY have text in the TextObject and not anything else (aka fields, parameters, formulas) ?
As far as I know the fields in a text box will be recognized by the text pattern. Try to search the text of the text object for {1#xxxxx} where xxxxx is the field name. "{1#" shows the type of the field: 1 is for a database , 2 is for formula, 3 is for parameter. You may try also for {#xxxxx} *(without numeric field identifier)
I searched alot around and found working solution for RAS report but nothing for crystal. Anyhow if someone end up here looking for an answer here's the work around.
Whenever you have to concatenate multiple fields on the report do NOT use TextObject. Instead use a Formula. The formula fields wont bet part of the ReportObjects but instead part of the ReportDocument.DataDefinition.FormulaFields with Kind being CrystalDecisions.Shared.FieldKind.FormulaField and you will want to check the ValueType so it is CrystalDecisions.Shared.FieldValueType.StringField.
then you can manipulate them.
I did need that for translation of report live so here's a parsing method for formulas :
try
{
var sFormula = formula.Text;
string pattern = "\"[\\w ]*\"";
Regex r = new Regex(pattern);
MatchCollection mc = r.Matches(sFormula);
foreach (Match m in mc)
{
var sValue =m.Value;
var sParsedValue = sValue.Substring(1, sValue.Length - 2);
if (sParsedValue.StartsWith("s"))
{
var stest = "\"" + CApplicationData.TranslateStringValue(sParsedValue) + "\"";
sFormula = sFormula.Replace(sValue, stest);
}
}
formula.Text = sFormula;
}
catch{}
this above you will notice i use 's' as a key to know it might be a value to be translated so it's not mandatory. using the above on this formula with Spanish language :
"sPage" + " " + totext(PageNumber) + " " + "sOf" + " " + totext(TotalPageCount)
will modify the formula to :
"Página" + " " + totext(PageNumber) + " " + "de" + " " + totext(TotalPageCount)
giving output of :
Página 1 de 4

adding space in texbox results when sending thru email

wassup guys im new to C# coding and i did a search but couldn't find exactly what im looking for. So i have a couple of text-boxes which holds string elements and integers
what i want to do is when these boxes are filled in i want to send a summary of the email to client/customer but the format is whats getting me.
(first, one) are strings equaling different text-boxes
my code is:
emailCompseTask.Body = first + one + Enviroment.NewLine +
second + two + Enviroment.NewLine
and so on problem is which i send thru email it shows something like this:
computer service25.00
instead of:
computer service 25.00
is there a way to add spacing to make this more presentable? or even a better way perhaps thanks in advance guys
try this :
emailCompseTask.Body = first + one + " "+ second + two ;
body takes as HTML input, check here for more spacing option.
I'm a bit confused, but you just want to add some spacing in the output? Just throw some spaces in there like you would another variable.
first + " " + one + Environment.NewLine
+ second + " " + two + Environment.NewLine;
You can use a table
string tableRow = #"<tr>
<td>{0}</td>
<td>{1}</td>
</tr>";
string htmlTable = #"<table>
{0}
</table>";
string rows = "";
// Can do this in a loop
rows += string.Format(tableRow, first, one);
rows += string.Format(tableRow, first, one);
emailComseTask.Body = string.Format(htmlTable, rows);

C# - Literal control vulnerable to XSS attack

I'm using a literal to display some javascript on a product page control. Basically what I'm doing is in my code behind I'm declaring a new stringbuilder, writing the script while inserting some dynamic variables to populate the script then setting the literal text to the stringbuilder. This leaves me open to xss attacks. What can I do to prevent this?
EDIT. Here is an example of the stringbuilder. when the page gets loaded the xss vulnerability occurs right after the javascript is generated.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//loop through items in the collection
for (int i = 0; i < _prod.ActiveProductItemCollection.Count; i++)
{
sb.Append("<script type='text/javascript'>");
//add +1 to each item
sb.AppendFormat("mboxCreate(\"product_productpage_rec{0}\",", i+1);
sb.Append("\"entity.id=" + _prodID + "\",");
sb.Append("\"entity.categoryId=" + _categoryID + "\",");
sb.Append("\"entity.name=" + _prod.ActiveProductItemCollection[i].Title + "\",");
sb.Append("\"entity.pageURL=" + Request.Url.ToString() + "\",");
//The following value has been taken from the productImageControl code behind.
//Might have to refactor in future as a property of the image control.
string filename = AppSettingsManager.Current.ProductImagePathLarge + _prod.ActiveProductItemCollection[i].Sku
+ AppSettingsManager.Current.ProductImageExtension;
sb.Append("\"entity.thumbnailURL=" + filename + "\",");
sb.Append("\"entity.inventory=" + _prod.ActiveProductItemCollection.Count + "\",");
sb.Append("\"entity.value=" + _prod.ActiveProductItemCollection[i].ActualPrice + "\",");
sb.Append("\"entity.ProductItemID=" + _prod.ActiveProductItemCollection[i].Sku + "\",");
sb.Append("\"entity.addToCartImg=~/Images/Buttons/btn_AddToCartFlat.gif\");<");
//The last line has to be /script. < inserted on prev line. do not change it or bad things will happen.
sb.Append("/script>");
}
this.LiteralMBoxScript.Text = sb.ToString();
You need to properly encode any user-generated data that you're putting into the Javascript.
In ASP.Net 4.0, you can call HttpUtility.JavaScriptStringEncode.
In earlier versions, you can use the Web Protection Library.
To prevent XSS you could HTML encode the value.
Alternately, you could write your javascript to read the user supplied data off of the page. This will result in less javascript code, and a faster page load.
If you are using JQuery for example, you can use the $.Parent() and $.Children() selectors to traverse the DOM to the appropriate form controls to reference information about that particular record in the loop.
Here is a relatively simple sample
function doSomething(context) {
var IDInput = $(context).parent('td').parent('tr').children('td.id').children('.hidden');
//Do something with the value
IDInput.val();
}
This would work with the following html example:
<table>
<tr>
<td><input type="button" onclick="doSomething(this)" value="Do Something"/></td>
<td class="id">Hidden ID Value <input type="hidden" value="1"/></td>
</tr>
<tr>
<td><input type="button" onclick="doSomething(this)" value="Do Something"/></td>
<td class="id">Hidden ID Value <input class="hidden" type="hidden" value="2"/></td>
</tr>
</table>
The advantage of doing it this way is that you no longer have to write javascript functions that take the ID as a parameter, meaning you don't need to dynamically generate the functions on the button, and can load them in the header in a separate JS file.
Well, if it is just your own script being written to the literal, you are no more open to attacks than if you simply included a js file on your site. If on the otherhand your script is interspersed with user supplied data of any kind, then you need to sanitize that data before you write it to the page.
If you are using .NET 4.0, you could output the value using the <%: theText %> syntax.

Categories

Resources